MongoDB聚合到$ group并有条件地$ addToSet

时间:2019-05-27 16:52:06

标签: mongodb aggregation-framework

鉴于以下虚拟集合,我想为给定资源提取出口和进口国家:

[{
    country: "France",
    exchange: {
        export: [{
            resource: "MILK",
            origin: ["Toulouse", "Bordeaux"]
        }],
        import: [{
            resource: "BEEF",
            origin: ["Lyon", "Marseille"]
        }]
    }
}, {
    country: "Spain",
    exchange: {
        export: [{
            resource: "PORK",
            origin: ["Madrid", "Barcelona"]
        }],
        import: [{
            resource: "MILK",
            origin: ["Valencia", "Bilbao"]
        }]
    }
}]

预期结果:

{
    resource: "MILK",
    exportingCountries: ["France"],
    importingCountries: ["Spain"]
}

我一直在和$group一起玩,但是我找不到找到有条件地$addToSet个国家/地区的方法。

1 个答案:

答案 0 :(得分:1)

您可以使用$concatArrays组合exchange.exportexchange.import数组。这样一来,您可以country$group,然后需要使用$filter$map运算符取回importexport,请尝试: / p>

db.col.aggregate([
    {
        $project: {
            country: 1,
            resources: {
                $concatArrays: [
                    { $map: { input: "$exchange.export", in: { resource: "$$this.resource", exchange: "export" } } },
                    { $map: { input: "$exchange.import", in: { resource: "$$this.resource", exchange: "import" } } },
                ]
            }
        }
    },
    {
        $unwind: "$resources"
    },
    {
        $group: {
            _id: "$resources.resource",
            resources: { $addToSet: { country: "$country", exchange: "$resources.exchange" } }
        }
    },
    {
        $project: {
            _id: 0,
            resource: "$_id",
            importingCountries: { 
                $map: { 
                    input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "import" ] } } },
                    in: "$$this.country" 
                } 
            },
            exportingCountries: { 
                $map: { 
                    input: { $filter: { input: "$resources", as: "r", cond: { $eq: [ "$$r.exchange", "export" ] } } },
                    in: "$$this.country" 
                } 
            }
        }
    }
])

输出:

{ "resource" : "PORK", "importingCountries" : [ ], "exportingCountries" : [ "Spain" ] }
{ "resource" : "BEEF", "importingCountries" : [ "France" ], "exportingCountries" : [ ] }
{ "resource" : "MILK", "importingCountries" : [ "Spain" ], "exportingCountries" : [ "France" ] }