首页 > 解决方案 > MongoDB使用聚合连接两个字段,其中实际字段位于数组中

问题描述

我有一个如下所示的 mongo 文档;

{
    "_id" : "123",
    "info" : {
        "batch" : "Batch1-Minor"
    },
    "batchElements" : {
        "elements" : [ 
             {
               "_id" : "elementId1",
               "type": "ABC"
             },  
             {
                "_id" : "elementId2",
                "type": "ABC"
             }
        ]
    }
}

如何通过连接和更改_id内部字段来生成聚合输出elements$info.batch$batchElements.elements._id

预期输出:

{
    "_id" : "123",
    "info" : {
        "batch" : "Batch1-Minor"
    },
    "batchElements" : {
        "elements" : [ 
             {
               "_id" : "Batch1-Minor-elementId1",
               "type": "ABC"
             },  
             {
                "_id" : "Batch1-Minor-elementId2",
                "type": "ABC"
             }
        ]
    }
}

标签: mongodbmongodb-queryaggregation-framework

解决方案


通过下面的查询,我们正在迭代& 用& batchElements.elements& 形成对象,最后会将对象数组推回将字段添加到实际文档的位置,试试这个:type_id$mapbatchElements.elements$addFields

db.yourCollectionName.aggregate([{
    $addFields: {
        'batchElements.elements': {
            $map:
            {
                input: "$batchElements.elements",
                as: "each",
                in: { type: '$$each.type', '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }
               /** So if you've multiple fields in each object then instead of listing all, You need to use 
                in: { $mergeObjects: ["$$each", { '_id': { $concat: ["$info.batch", "-", "$$each._id"] } }] } */
            }
        }
    }
}])

推荐阅读