MongoDB - 更新嵌套数组中的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34431435/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB - Update an object in nested Array
提问by u5598875
{
"_id": "xPBc4By8FemDwTPqH",
"u": {
"_id": "6PoZawHZcQz4Gwzcv",
"username": "michael"
},
"friends": [
{
"u": {
"_id": "eGqDjAjjtYADbuSnn",
"username": "michael",
"name": "michael"
}
},
{
"u": {
"_id": "k4gKCGwYryXDMMHvs",
"username": "joyce",
"name": "joyce"
}
}
]
}
I want to update the name of "friends.u.username": "michael" 's name is "hello", how I need to do it.
我想更新“friends.u.username”的名字:“michael”的名字是“hello”,我需要怎么做。
回答by chridam
Apply the $set
operator together with the $
positional operatorin your update to change the name
field.
在更新中将$set
运算符与$
位置运算符一起应用以更改name
字段。
The $
positional operatorwill identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like:
该$
位置操作者将确定阵列更新的正确元而不显式指定数组中元素的位置,从而最终update语句应该是这样的:
db.collection.update(
{ "friends.u.username": "michael" },
{ "$set": { "friends.$.u.name": "hello" } }
)
回答by Srivatsa N
You can use $set operator.
您可以使用 $set 运算符。
> db.test.update({"friends.u._id":"eGqDjAjjtYADbuSnn"},{$set:{"friends.$.u.name":"hello"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
回答by Sanjay Bharwani
Below should work fine as its tested
下面应该可以正常工作
First check the current value of the array.
首先检查数组的当前值。
db.test.findOne({"friends.u.id" : "eGqDjAjjtYADbuSnn"},{"friends.u.name":1})
Now fire the update command
现在启动更新命令
db.test.update({"friends.u.id" : "eGqDjAjjtYADbuSnn"},{$set:{"friends.$.u.name":"hello"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Now check the results again to validate the update values
现在再次检查结果以验证更新值
db.test.findOne({"friends.u.id" : "eGqDjAjjtYADbuSnn"},{"friends.u.name":1})
Hope this helps.
希望这可以帮助。