MongoDB update data in nested field

allen wang picture allen wang · Oct 26, 2013 · Viewed 69.9k times · Source

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.

Answer

Cristian Lupascu picture Cristian Lupascu · Oct 26, 2013

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.