MongoDB: updating a document in an array

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 am trying to execute this command:

 db.messages.findAndModify({query:{'recipients.id':2}, update:{'recipients.$.isread':true}}) 

but what he does is, he simply replaces the entire recipient field with the $ recipients. isread ", so now the document looks like this:

 { _id: someid, 'recipients.$.isread':true } 

What am I doing wrong?

+6
source share
1 answer

Try using $ set as follows:

 db.messages.findAndModify({query:{'recipients.id':2}, update:{$set:{'recipients.$.isread':true}}}) 
+7
source

Source: https://habr.com/ru/post/891247/


All Articles