您可以更新內嵌的「銷售」文檔「 act_mgr」陣列以下更新語句:
> db.sales.update({"act_mgr.sales.last_interacted":"[email protected]"}, {$push:{"act_mgr.$.sales.agent":"[email protected]"}, $set:{"act_mgr.$.sales.last_interacted":"[email protected]"}})
> db.sales.find().pretty()
{
"_id" : ObjectId("4f855061dd53351011000b42"),
"act_mgr" : [
{
"sales" : {
"agent" : [
"[email protected]",
"[email protected]"
],
"last_interacted" : "[email protected]"
}
}
],
"email" : "[email protected]",
"name" : "Aman",
"sales" : [
{
"sno" : 1,
"message" : "description",
"status" : "open"
},
{
"sno" : 12,
"message" : "assad",
"status" : "open"
}
]
}
>
可以將包含嵌入的文檔添加‘開發商’信息發送到陣列像這樣:
> db.sales.update({"_id" : ObjectId("4f855061dd53351011000b42")}, {$push:{"act_mgr":{ "developer" : {"agent" : ["[email protected]" ], "last_interacted" : "[email protected]" } }}})
> db.sales.find().pretty()
{
"_id" : ObjectId("4f855061dd53351011000b42"),
"act_mgr" : [
{
"sales" : {
"agent" : [
"[email protected]",
"[email protected]"
],
"last_interacted" : "[email protected]"
}
},
{
"developer" : {
"agent" : [
"[email protected]"
],
"last_interacted" : "[email protected]"
}
}
],
"email" : "[email protected]",
"name" : "Aman",
"sales" : [
{
"sno" : 1,
"message" : "description",
"status" : "open"
},
{
"sno" : 12,
"message" : "assad",
"status" : "open"
}
]
}
>
在$推動和$組修飾符的文檔可以在「更新」文件中找到: http://www.mongodb.org/display/DOCS/Updating
創建和更新與蒙戈DB嵌入文檔的更多信息可以在文檔中找到標題爲「點標記(將手伸入對象)」 http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29
上更新使用「$」位置操作者嵌入文檔的信息可以在「更新」文檔「的$位置運算符」一節中找到。
http://www.mongodb.org/display/DOCS/Updating#Updating-The%24positionaloperator
警告一句話:嵌入式文檔全部匹配相同的結構通常比較普遍,因此可以更容易地引用各個嵌入式文檔。你的「銷售」陣列就是一個很好的例子。每個嵌入文檔包含相同的密鑰「sno」,「消息」和「狀態」
但是,「act_mgr」數組中的嵌入文檔包含不同的鍵;第一個包含「銷售」,第二個包含「開發者」。相反,也許考慮以下結構:
"act_mgr" : [
{
"title" : "sales",
"agent" : [
"[email protected]",
"[email protected]"
],
"last_interacted" : "[email protected]"
},
{
"title": "developer",
"agent" : [
"[email protected]"
],
"last_interacted" : "[email protected]"
}
]
現在,每一個嵌入文檔包含相同的鑰匙,「標題」,「代理」,及「last_interacted」。
您可以使用以下命令更新子文檔。
> db.sales.update({"act_mgr.title":"sales"}, {$push:{"act_mgr.$.agent":"[email protected]"}, $set:{"act_mgr.$.last_interacted":"[email protected]"}})
希望這可以讓你做出你需要的更新,也許會給你一些關於模式設計的思考。祝你好運!
檢查這個'http:// stackoverflow.com/questions/9611833/mongodb-updates-fields-in-nested-array/10412311#10412311' – 2012-05-02 11:00:59
重複或許,但這個問題和答案比早先的更清楚。 – 2014-12-17 15:19:33