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.
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.
update something in a multi level arry is really pain in the ass, my way of doing it:replace the deep level arry.
db.user.findOne({_id:'123'},{friends:1}).lean().exec(function(err,user){
var whichArrayToUpdate;
for (var ii = 0; ii < user.friends.length; ii++) {
for (var jj = 0; i < user.friends[ii].emails; jj++) {
if(user.friends[ii].emails[jj].email == '1111' ){// update it below
user.friends[ii].emails[jj].email == 'what ever you want to set to.';
whichArrayToReplace = user.friends[ii].emails;
break;
}
};
};
db.user.update({'friends.name':'allen'},{$set{'friends.$.email': whichArrayToReplace} })
})
but, why not use the save() method? the save() will replace your whole document, if your document is small that's ok, but if your document is relly big , it's a better idea to replace just part of your document.
or do the loop, use the position of the top level array and second level array(ii and jj) to update.
my advice is: when you design schema, don't put array in another array unless you won't do any update for that array.
Solution using Mongoose:
Users.findById("123", function(err, user) {
var friends = user.friends;
for ( i=0; i < friends.length; i++ ) {
if (friends[i].name == 'allen') {
friends[i].email = '2222';
user.save(function(err) {
if (err) throw err;
console.log("email updated");
});
} else {
console.log("no friends named allen");
}
}
}