I have a collection with documents of this schema:
{
_id: something,
recipients: [{id:1, name:"Andrey", isread:false}, {id:2, name:"John", isread:false}]
}
Now, I want to update "isread" for John (id = 2) using findAndModify()
, because I also need to get the original document.
I'm trying this command:
db.messages.findAndModify({query:{'recipients.id':2}, update:{'recipients.$.isread':true}})
but what it does, it just replaces the whole "recipients" field with 'recipients.$.isread', so the document now looks like:
{
_id: someid,
'recipients.$.isread':true
}
What am I doing wrong?
To update all the elements of an array, call the forEach() method on the array, passing it a function. The function gets called for each element in the array and allows us to update the array's values.
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
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.
Try to use $set like this:
db.messages.findAndModify({query:{'recipients.id':2}, update:{$set:{'recipients.$.isread':true}}})
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