您可以更新内嵌的“销售”文档“ 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