Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating embedded document property in Mongodb

Tags:

mongodb

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?

like image 514
ajma Avatar asked Jul 20 '11 07:07

ajma


People also ask

How do you update one property in MongoDB?

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.

How do I update an embedded array in MongoDB?

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.

What is embedded document in MongoDB?

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.


2 Answers

.update(Authors:{$elemMatch:{Slug:"slug"}}, {$set: {'Authors.$.Name':"zzz"}}); 
like image 165
Remon van Vliet Avatar answered Oct 10 '22 22:10

Remon van Vliet


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.

like image 22
Rock Avatar answered Oct 10 '22 21:10

Rock