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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With