2012-07-07 25 views
40

我試圖更新MongoDB文檔中的數組中包含的單個子元素。我想使用它的數組索引來引用該字段(數組中的元素沒有任何字段,我可以保證它們是唯一標識符)。似乎這應該很容易做到,但我無法弄清楚語法。MongoDB:如何更新數組中的單個子元素,由數組中的索引引用?

這就是我想在僞json中做的事情。

前:

{ 
    _id : ..., 
    other_stuff ... , 
    my_array : [ 
    { ... old content A ... }, 
    { ... old content B ... }, 
    { ... old content C ... } 
    ] 
} 

後:

{ 
    _id : ..., 
    other_stuff ... , 
    my_array : [ 
    { ... old content A ... }, 
    { ... NEW content B ... }, 
    { ... old content C ... } 
    ] 
} 

好像查詢應該是這樣的:

//pseudocode 
db.my_collection.update(
    {_id: ObjectId(document_id), my_array.1 : 1 }, 
    {my_array.$.content: NEW content B } 
) 

但是,這是行不通的。我花了太長時間搜索mongodb文檔,並試圖對此語法進行不同的修改(例如,使用$slice等)。我找不到任何關於如何在MongoDB中完成這種更新的明確說明。

回答

51

正如預期的那樣,一旦你知道如何,查詢很容易。這裏是Python中的語法:

db["my_collection"].update(
    { "_id": ObjectId(document_id) }, 
    { "$set": { 'documents.'+str(doc_index)+'.content' : new_content_B}} 
) 
+9

否.. ..它是真的不明。 – Moumit 2015-04-30 19:49:15

10

在mongo風格中,使用'$'位置運算符。 查看詳情link

db.my_collection.update(
    {_id: ObjectId(document_id), my_array.1 : 1 }, 
    { $set: { "my_array.$.content" : "NEW content B" } } 
) 
19

由索引參照的數組元素的更新(例如,1)在蒙戈殼牌還可以通過直接表示所述指標值來完成:

db.my_collection.update(
    {_id : "document_id"}, 
    {$set : {"my_array.1.content" : "New content B"}} 
) 
0
db.my_collection.update(
    {_id: ObjectId(document_id), my_array : { ... old content A ... } }, 
    { $set: { "my_array.$.content" : "NEW content B" } } 
) 
相關問題