Andrey
Andrey

Reputation: 21285

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'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?

Upvotes: 7

Views: 3049

Answers (1)

kheya
kheya

Reputation: 7622

Try to use $set like this:

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

Upvotes: 7

Related Questions