Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a sub-document in mongodb?

Tags:

How do I target an subdocument in the authors array as shown below, in order to update it?

collection.update({'_id': "4f44af6a024342300e000001"}, {$set: { 'authors.?' }} ) 

The document:

{     _id:     "4f44af6a024342300e000001",     title:   "A book",      created: "2012-02-22T14:12:51.305Z"     authors: [{"_id":"4f44af6a024342300e000002"}]  } 
like image 490
Industrial Avatar asked Feb 22 '12 19:02

Industrial


People also ask

Can we update document in MongoDB?

To update a document in MongoDB, we use the update() method. The update() method refreshes the values in a MongoDB collection's existing document. The _id field's value does not change when you update your document.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


1 Answers

By specifying actual position of embedded document like this:

// update _id field of first author     collection.update({'_id': "4f44af6a024342300e000001"},                    {$set: { 'authors.0._id': "1" }} ) 

Or via positional operator:

// update _id field of first matched by _id author     collection.update({'_id': "4f44af6a024342300e000001",                     //you should specify query for embedded document                     'authors._id' : "4f44af6a024342300e000002" },       // you can update only one nested document matched by query                                        {$set: { 'authors.$._id': "1" }} ) 
like image 51
Andrew Orsich Avatar answered Sep 23 '22 23:09

Andrew Orsich