2016-08-17 34 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" 
      }] 
     } 
    } 
}) 
相關問題