MongoDB:更新数组中的文档 [英] MongoDB: Updating a document in an array

查看:78
本文介绍了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}]
}

现在,我想使用findAndModify()为John(id = 2)更新"isread",因为我还需要获取原始文档.

Now, I want to update "isread" for John (id = 2) using findAndModify(), because I also need to get the original document.

我正在尝试以下命令:

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

但是它的作用是,它只是将整个收件人"字段替换为"recipients.$.isread",因此文档现在看起来像:

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
}

我在做什么错了?

推荐答案

尝试像这样使用$ set:

Try to use $set like this:

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

这篇关于MongoDB:更新数组中的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆