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

时间:2016-02-25 09:56:37

标签: 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,
        }
    ]
}

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

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

1 个答案:

答案 0 :(得分: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}});
     });