Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB update data in nested field

Tags:

mongodb

nested

i'm using Mongo to be my database. i have a data:

 {    _id : '123'    friends: [      {name: 'allen', emails: [{email: '11111', using: 'true'}]}    ]  } 

now, i wanna to motify user's friends' emails ' email, whose _id is '123' i write like this:

db.users.update ({_id: '123'}, {$set: {"friends.0.emails.$.email" : '2222'} }) 

it's easy, but , it's wrong , when the emails array has two or more data. so, my question is: how can i motify the data in a nested filed --- just have two or more nested array? Thanks.

like image 301
allen wang Avatar asked Oct 26 '13 06:10

allen wang


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.

Is it possible to update MongoDB field using value of another field?

The way we do this is by $project ing our documents and using the $concat string aggregation operator to return the concatenated string. You then iterate the cursor and use the $set update operator to add the new field to your documents using bulk operations for maximum efficiency.


1 Answers

You need to use the Dot Notation for the arrays.

That is, you should replace the $ with the zero-based index of the element you're trying to update.

For example:

db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.0.email" : '2222'} }); 

will update the first email of the first friend, and

db.users.update ({_id: '123'}, { '$set': {"friends.0.emails.1.email" : '2222'} }) 

will update the second email of the first friend.

like image 91
Cristian Lupascu Avatar answered Sep 20 '22 08:09

Cristian Lupascu