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?
To update a single field or specific fields just use the $set operator. This will update a specific field of "citiName" by value "Jakarta Pusat" that defined by $set operator.
To perform an update on all embedded array elements of each document that matches your query, use the filtered positional operator $[<identifier>] . The filtered positional operator $[<identifier>] specifies the matching array elements in the update document.
MongoDB provides you a cool feature which is known as Embedded or Nested Document. Embedded document or nested documents are those types of documents which contain a document inside another document.
.update(Authors:{$elemMatch:{Slug:"slug"}}, {$set: {'Authors.$.Name':"zzz"}});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With