Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Update an object in nested Array

{   "_id": "xPBc4By8FemDwTPqH",   "u": {     "_id": "6PoZawHZcQz4Gwzcv",     "username": "michael"   },   "friends": [     {       "u": {         "_id": "eGqDjAjjtYADbuSnn",         "username": "michael",         "name": "michael"       }     },     {       "u": {         "_id": "k4gKCGwYryXDMMHvs",         "username": "joyce",         "name": "joyce"       }     }   ] } 

I want to update the name of "friends.u.username": "michael" 's name is "hello", how I need to do it.

like image 333
徐巧民 Avatar asked Dec 23 '15 08:12

徐巧民


People also ask

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.

How do you update an object in an array of objects in MongoDB?

MongoDB syntax for updating an object inside an array within a document? For this, use findOneAndUpdate() in MongoDB. The findOneAndUpdate() method updates a single document based on the filter and sort criteria.

How do I change the value of nested objects in MongoDB?

To update more than one array item matching the criteria in this way, then you need to issue the update several times until the document is no longer modified. So the index position is 0 for the first element, 1 for the second element and so on.


1 Answers

Apply the $set operator together with the $ positional operator in your update to change the name field.

The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array, thus your final update statement should look like:

db.collection.update(     { "friends.u.username": "michael" },      { "$set": { "friends.$.u.name": "hello" } } ) 
like image 99
chridam Avatar answered Oct 01 '22 08:10

chridam