Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Updating a document in an array

Tags:

mongodb

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?

like image 615
Andrey Avatar asked Jun 23 '11 20:06

Andrey


People also ask

How do you update data in an array?

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.

How do I push data into an array in MongoDB?

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.

How do I update a nested array in MongoDB?

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.


1 Answers

Try to use $set like this:

db.messages.findAndModify({query:{'recipients.id':2}, update:{$set:{'recipients.$.isread':true}}})
like image 140
kheya Avatar answered Sep 18 '22 14:09

kheya