2016-08-17 56 views
-1

我正在使用PyMongo并且集合中的文档有一个字段是这样的对象数组的文档是更新集合中的嵌入式文档在末尾添加元素

{ 
    "_id" : ObjectId("509df76fbcf1bf5b27b4a23e"), 
    "field1" : "asfasfdas", 
    "field2" : "asfasdfa", 
    "embedded" : [ 
     { "field1" : "asdfasdf", "field2" : "asdfasdfa" }, 
     { "field1" : "asdfasfth.", "field2" : "asdfasf" } 
    ] 
} 

所以我想在embedded的字段中添加一个新对象。我可以用什么方法来实现这一目标?

+0

['update_one'(http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection。 update_one)或['update_many'](http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.update_many),具体取决于你想要做什么。你还需要['$ push'](https://docs.mongodb.com/manual/reference/operator/update/push/)运营商 – styvane

+0

你能举个例子吗? – provola

回答

1

使用更新查询和$推

db.collection.update({ 
    _id: "509df76fbcf1bf5b27b4a23e" 
}, { 
    $push: { 
     embedded: { 
      $each: [{ 
       "field1": "test1", 
       "field2": "test1" 
      } { 
       "field1": "test2", 
       "field2": "test2" 
      }] 
     } 
    } 
})