更新 Mongodb 中的嵌入文档属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6758339/
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
Updating embedded document property in Mongodb
提问by ajma
I have a document that looks like this:
我有一个看起来像这样的文档:
{
"_id": 3,
"Slug": "slug",
"Title": "title",
"Authors": [
{
"Slug": "slug",
"Name": "name"
}
]
}
I want to update all Authors.Name based on Authors.Slug. I tried this but it didn't work:
我想根据 Authors.Slug 更新所有 Authors.Name。我试过这个,但没有用:
.update({"Authors.Slug":"slug"}, {$set: {"Authors.Name":"zzz"}});
What am I doing wrong here?
我在这里做错了什么?
回答by Remon van Vliet
.update(Authors:{$elemMatch:{Slug:"slug"}}, {$set: {'Authors.$.Name':"zzz"}});
回答by Rock
You can use update with array filters:
https://docs.mongodb.com/manual/reference/operator/update/positional-filtered/#positional-update-arrayfilters
您可以将更新与数组过滤器一起使用:https:
//docs.mongodb.com/manual/reference/operator/update/positional-filtered/#positional-update-arrayfilters
Probably something like this:
大概是这样的:
yourcollection.update(
{},
{
"$set": {
"Authors.$[element].Name": "zzz"
}
},
{
"multi": true,
"arrayFilters": [
{ "element.Slug": "slug" }
]
}
)
Ps.: it will not work in Robo3Tas explained here: Mongodb 3.6.0-rc3 array filters not working?However, you can try on a mongo shell with version >= 3.6.
Ps.:它在 Robo3T 中不起作用,如下所述:Mongodb 3.6.0-rc3 array filters not working? 但是,您可以尝试使用版本 >= 3.6 的 mongo shell。
回答by joel Raja
yes, Rock's solution is working, P.S Notes is really helpful when trying Robo31.. If we want to update all db.collection_name.update({}, {$set: {"Authors.$[].Name": "zzz"}})
是的,Rock 的解决方案是有效的,PS Notes 在尝试 Robo31 时非常有用。如果我们想更新所有 db.collection_name.update({}, {$set: {"Authors.$[].Name": "zzz" }})
If we want to update with matching object in an array db.collection_name.update({}, {$set: {"Authors.$[i].Name": "zzz"}}, {arrayFilters: [{"i.Slug": "slug"}]})
如果我们想用数组 db.collection_name.update({}, {$set: {"Authors.$[i].Name": "zzz"}}, {arrayFilters: [{"i.弹头": "弹头"}]})