pymongo syntax to update a subdocument

你离开我真会死。 提交于 2019-12-23 03:43:09

问题


My documents look like this:

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

  }
}

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]

I try to do an update through pymongo

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

I get this exception

<type 'exceptions.TypeError'>

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?


回答1:


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}})


来源:https://stackoverflow.com/questions/13894769/pymongo-syntax-to-update-a-subdocument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!