开发者

MongoDB: Updating a document in an array

开发者 https://www.devze.com 2023-03-14 20:27 出处:网络
I have a collection with documents of this schema: { _id: something, recipients: [{id:1, name:\"Andrey\", isread:false}, {id:2, name:\"John\", isread:false}]

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 开发者_StackOverflowJohn (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?


Try to use $set like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消