How can I update the sub document field from the sub document array based on the query?

别等时光非礼了梦想. 提交于 2019-12-11 09:09:09

问题


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

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
    }
]
}

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?


回答1:


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}})

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



来源:https://stackoverflow.com/questions/29667369/how-can-i-update-the-sub-document-field-from-the-sub-document-array-based-on-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!