简体   繁体   English

Mongo聚合添加到子元素

[英]Mongo aggregation add to subelement

I got document like 我有类似的文件

{
    "_id" : ObjectId("5756c699fc5a2a09308a1c97"),
    "bucket" : [ 
        {
            "productid" : "Book1",
            "name" : "Sample Book1"
        }, 
        {
            "productid" : "Book2",
            "name" : "Sample Book 2"
        }
    ],
    "creatorId" : "c6c3a8f3"
}

Is there any way by which I can add creatorId to each item in the bucket and get the resultant as this: 有什么方法可以将creatorId添加到存储桶中的每个项目,并按以下方式获取结果:

{
    "_id" : ObjectId("5756c699fc5a2a09308a1c97"),
    "bucket" : [ 
        {
            "productid" : "Book1",
            "name" : "Sample Book1",
             "creatorId" : "c6c3a8f3"
        }, 
        {
            "productid" : "Book2",
            "name" : "Sample Book 2",
             "creatorId" : "c6c3a8f3"
        }
    ]

}

You can use aggregation framework for that, if you are going to reshape your collection - then un-comment $out phase of aggregation pipeline and result will be stored in collection newCollectionName 您可以使用聚合框架来实现此目的,如果您要调整集合的形状,则取消注释聚合管道的$ out阶段,结果将存储在集合newCollectionName

db.andrej.aggregate([{
            $unwind : "$bucket"
        }, {
            $group : {
                _id : "$_id",
                bucket : {
                    $push : {
                        productid : "$bucket.productid",
                        name : "$bucket.name",
                        creatorId : "$creatorId"
                    }
                }
            }
        },
        //{$out:"newCollectionName"}
    ])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM