Reputation: 12206
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:
.update({"Authors.Slug":"slug"}, {$set: {"Authors.Name":"zzz"}});
What am I doing wrong here?
Upvotes: 32
Views: 36312
Reputation: 69
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"}})
If we want to update with matching object in an array db.collection_name.update({}, {$set: {"Authors.$[i].Name": "zzz"}}, {arrayFilters: [{"i.Slug": "slug"}]})
Ref: https://jira.mongodb.org/browse/SERVER-1243
Upvotes: 0
Reputation: 21
You can use update with array filters:
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 Robo3T as explained here: Mongodb 3.6.0-rc3 array filters not working? However, you can try on a mongo shell with version >= 3.6.
Upvotes: 2
Reputation: 18595
.update(Authors:{$elemMatch:{Slug:"slug"}}, {$set: {'Authors.$.Name':"zzz"}});
Upvotes: 61