Pymongo how to properly use $push to update an existing document

北城余情 提交于 2019-12-10 17:06:49

问题


I am doing something wrong or I don't understand $push (probably don't understand). Anyway I have the following document:

{ "_id" : ObjectId("501c83051d41c8753e000000"), 
   "node" : "denver", 
   "enc" : { "environment" : "production", "classes" : { "denver" : "" } }, 
   "inherit" : "default" }

And I am trying to make the document

{ "_id" : ObjectId("501c83051d41c8753e000000"), 
  "node" : "denver", 
  "enc" : { "environment" : "production", 
  "classes" : { "denver" : "", "boulder" : ""} }, 
  "inherit" : "default" }

This is what my update statement looks like:

col.update({ 'node' : 'denver'}, 
           { '$push': { 'enc.classes' : {'boulder': ''}}},
           True)

I don't get an error but the document never updates. If I change $push to $set then the denver is replaced with boulder.

Thanks for any assistance.


回答1:


This query works.

db.foo.update({"node": "denver"}, {"$set": {"enc.classes.boulder": ""}}



回答2:


$push does not work in this case because you are trying to use an array function on an object.

To use $push you would need to change your data structure to the following:

{
    "_id" : ObjectId("501c83051d41c8753e000000"), 
    "node" : "denver", 
    "enc" : {
        "environment" : "production", 
        "classes" : [
            "denver"
        ]
    }, 
    "inherit" : "default"
}

Then your query would be:

col.update(
    {
        'node' : 'denver'
    },
    {
        '$push': {
            'enc.classes' : 'boulder'
        }
    },
    True
)


来源:https://stackoverflow.com/questions/11809663/pymongo-how-to-properly-use-push-to-update-an-existing-document

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