Update multiple subdocument without exact sub document level condition

元气小坏坏 提交于 2019-12-08 04:43:24

问题


I have collection with the following document:

{
    "_id" : ObjectId("56cbf9cd75de3ee9057b23c7"),
    "title" : "Abc",
    "comments" : [
        {
            "_id" : "",
            "message" : "",
            "active" : 1,
            "status" : 1,
        },
        {
            "_id" : "",
            "message" : "",
            "active" : 0,
            "status" : 1,
        },
        {
            "_id" : "",
            "message" : "",
            "active" : 1,
            "status" : 1,

        }
    ],

}
{
    "_id" : ObjectId("553744ae75de3eb9128b4568"),
    "title" : "Jhon",
    "comments" : [
        {
            "_id" : "",
            "message" : "",
            "active" : 1,
            "status" : 1,
        }
    ]
}

I need to update all status of comments as 0 where comments.active=1. I tried to solve it as below, but only first record of the comments is updated. Please help me..

db.comments.update({'comments.active':1},{$set:{'comments.$.status':0}})

回答1:


Per this issue New operator to update all matching items in an array, currently there is no operation to do that in mongodb. Feel so sad, this issue lasts for 6 years.

There could be one work around in mongo shell as below.

> db.comments
    .find({})
    .forEach(function(doc) { 
                        doc.comments.map(function(c) {
                                if (c.active == 1) {
                                    c.status = 0;
                                 }
                        }); 
                        db.comments.update(
                                      {_id: doc._id}, 
                                      {$set: {comments: doc.comments}});
     });


来源:https://stackoverflow.com/questions/35623891/update-multiple-subdocument-without-exact-sub-document-level-condition

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