Mongo聚合可根据字段名称

时间:2020-01-16 12:13:19

标签: mongodb mongodb-query aggregation-framework

我有一个汇总的mongo文档,如下所示。有两个不同的批次(“ -次要”和“ -主要”),每个批次也具有“ batchElements”。

{
    "_id" : "123",
    "info" : {
        "batch" : "Batch1-Minor"
    },
    "batchElements" : {
        "elements" : [ 
             { },  { }, .... { }
        ]
    }
},
{
    "_id" : "123",
    "info" : {
        "batch" : "Batch2-Minor"
    },
    "batchElements" : {
        "elements" : [ 
             { },  { }, .... { }
        ]
    }
},
{
    "_id" : "123",
    "info" : {
        "batch" : "Batch3-Major"
    },
    "batchElements" : {
        "elements" : [ 
             { },  { }, .... { }
        ]
    }
},
{
    "_id" : "123",
    "info" : {
        "batch" : "Batch4-Major"
    },
    "batchElements" : {
        "elements" : [ 
             { },  { }, .... { }
        ]
    }
}

如何收集“ -次要”和“ -主要”的所有“ batchElements”并创建如下文档;

输出:

  {
    "_id" : "123",
    "minorElements" : [
        [{}, {}, {}, ..... {} ], // elements of "Batch1-Minor"
        [{}, {}, {}, ..... {} ], // elements of "Batch2-Minor"
        ...                      // elements of "BatchN-Minor"
    ],
    "majorElements" : [
        [{}, {}, {}, ..... {} ], // elements of "Batch3-Major"
        [{}, {}, {}, ..... {} ], // elements of "Batch4-Major"
        ...                      // elements of "BatchN-Major"
    ]
}

1 个答案:

答案 0 :(得分:2)

您可以从$split开始,将批次的“类型”作为$group _id的一部分。然后,您可以运行另一个$group以使同一文档的minormajor组成部分。在最后一步中,您需要$replaceRoot$arrayToObject一起将两个数组提升为根级别。

db.collection.aggregate([
    {
        $group: {
            _id: {
                id: "$_id",
                type: { $arrayElemAt: [ { $split: [ { $toLower: "$info.batch" }, "-" ] }, 1 ] }
            },
            docs: { $push: "$batchElements.elements" }
        }
    },
    {
        $group: {
            _id: "$_id.id",
            data: { $push: { k: { $concat: ["$_id.type","Elements"] }, v: "$docs" } }
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [ { _id: "$_id" }, { $arrayToObject: "$data" } ]
            }
        }
    }
])

Mongo Playground