如何根据查询从子文档数组更新子文档字段? [英] How can I update the sub document field from the sub document array based on the query?

查看:109
本文介绍了如何根据查询从子文档数组更新子文档字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{
"_id": ObjectId("552cd780e4b042752e540df5"),
"source": [
    {
        "bookid": ObjectId("552cd77e31456e192df6ad8e"),
        "isActive": false
    },
    {
        "bookid": ObjectId("552cd77e31456e192df6ad8a"),
        "isActive": true
    }
]
}

我需要更新上述文档,条件是source.bookidObjectId("552cd77e31456e192df6ad8e"),并将该特定文档字段isActive更新为false.因此,我需要的结果输出为

I need to update the above document , where the condition is the source.bookid is ObjectId("552cd77e31456e192df6ad8e") and update that particular document field isActive as false. So, the resulting output I need as

{
"_id": ObjectId("552cd780e4b042752e540df5"),
"source": [
    {
        "bookid": ObjectId("552cd77e31456e192df6ad8e"),
        "isActive": false
    },
    {
        "bookid": ObjectId("552cd77e31456e192df6ad8e"),
        "isActive": true
    }
]
}

任何人都可以告诉我,如何执行此更新查询?还能检索子文档数组包含所有"isActive"为false的所有文档吗?

Can anyone please tell me , how to execute this update query? and also is it possible to retrieve all documents where the sub docments array contains all "isActive" as false?

推荐答案

使用 mongo更新文档用于嵌套密钥更新,请使用如下所示的$elemMatch查询

Use mongo update documentation for nesting key update use $elemMatch query as below

db.collectionName.update({"source":{"$elemMatch":{"bookid":ObjectId("552cd77e31456e192df6ad8e")}}},{"$set":{"source.$.isActive":false}})

如果要更新多个文档,则使用此 mongo更新添加多个true.

If multiple document update then used this mongo update add multi true.

这篇关于如何根据查询从子文档数组更新子文档字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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