1

我收集了以下文件:

{
    "_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}})
4

1 回答 1

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}});
     });
于 2016-02-25T10:51:06.067 回答