在没有确切的子文档级别条件的情况下更新多个子文档 [英] Update multiple subdocument without exact sub document level condition

查看:93
本文介绍了在没有确切的子文档级别条件的情况下更新多个子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经收集了以下文件:

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

我需要将所有评论状态更新为 0 ,其中 comments.active = 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}})

推荐答案

此问题 New operator to update all matching items in an array ,目前在mongodb中没有操作可以做到这一点.感到很难过,这个问题持续了6年.

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.

在mongo shell中可能有一种解决方法,如下所示.

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

这篇关于在没有确切的子文档级别条件的情况下更新多个子文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆