Search code examples
mongodbnested

How can I update a property of an object that is contained in an array of a parent object using mongodb?


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

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

now, i wanna to modify 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 modify the data in a nested filed --- just have two or more nested array? Thanks.


Solution

  • 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.