pymongo语法更新子文档 [英] pymongo syntax to update a subdocument

查看:285
本文介绍了pymongo语法更新子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档如下:

{
  a: "..."
  subdocs [
    {
      l: "..."
      m: "..."
      n: 0
    },
    {
      l: "..."
      m: "..."
      n: 0
    }

  }
}

我必须使用pymongo更新特定子文档中的'n'字段.我有文档和子文档的索引,所以我可以得到这样的子文档

I have to update the 'n' field in a particular subdoc using pymongo. I have the document and the index of the subdocument so I can get the subdoc like this

subdoc = mydoc['subdocs'][index]

我尝试通过pymongo进行更新

I try to do an update through pymongo

coll.update( { mydoc['subdocs'][index] : subdoc }, { "$inc": { n: 1 }} )

我得到这个例外

<type 'exceptions.TypeError'>

我对此进行了多种尝试,但无法正确使用pymongo语法.我认为我的查询文件不正确. pymongo对这种语法有什么期望?

I've tried several variations on this and can't get the pymongo syntax right. I think my query document is incorrect. What does pymongo expect for this syntax?

推荐答案

您需要使用以下这样的点符号来标识要在第二个参数中更新为update的数组元素:

You need to identify the array element to update in the second parameter to update using dot notation like this:

coll.update({'_id': mydoc['_id']}, {'$inc': {'subdocs.' + str(index) + '.n': 1}})

这篇关于pymongo语法更新子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆