更新多个子文档,没有确切的子文档级别条件

KTA*_*Anj 1 mongodb mongodb-query mongodb-update

我收集了以下文件:

{
    "_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,
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我需要将注释的所有状态更新为0,其中comments.active = 1.我尝试解决它,如下所示,但只更新了评论的第一条记录.请帮我..

db.comments.update({'comments.active':1},{$set:{'comments.$.status':0}})
Run Code Online (Sandbox Code Playgroud)

zan*_*ngw 7

根据这个问题New operator to update all matching items in an array,目前在mongodb中没有这样做的操作.感到非常难过,这个问题持续了6年.

mongo shell可以有一个解决方法,如下所示.

> 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}});
     });
Run Code Online (Sandbox Code Playgroud)