如何在组内推送多列的值

时间:2015-04-08 09:49:27

标签: mongodb aggregation-framework

似乎我的查询不会像我期望的那样

我希望按name进行分组,并将location1和location2映射到名为locations的数组

数据

{name: "Jack", localtion1: "Taiwan", localtion2: "France"},
{name: "Jack", localtion1: "Japan", localtion2: "Taiwan"},
{name: "Mary", localtion1: "China", localtion2: "Taiwan"}

预期结果

{
    name: "Jack",
    localtions: ["Taiwan", "France", "Japan"]
},
{name: "Mary", localtions: ["China", "Taiwan"]}

查询

db.collection.aggregate([
    {
        $group: {
            _id: "$name",
            "localtions":{
                $addToSet: "$localtion1"
            },
            "localtions":{
                $addToSet: "$localtion2"
            }            
            count: { $sum: 1 }
        }
    },
    {
        $project: {
            name: "$_id",
            localtions: "$localtions",
            _id: 0
        }
    },    
])

2 个答案:

答案 0 :(得分:7)

您可以使用$setUnion运算符。对于其他设置运算符,请阅读this

db.collection.aggregate([
        {
            "$group": {
                "_id": "$name", 
                "localtion1": { "$addToSet": "$localtion1" }, 
                "localtion2": { "$addToSet": "$localtion2" }
             }
        },
        { 
            "$project": {
                "name": "$_id", 
                "localtions": { "$setUnion": [ "$localtion1", "$localtion2" ] }, 
                "_id": 0
            }
        }
])

<强>输出

{ "name" : "Mary", "localtions" : [ "Taiwan", "China" ] }
{ "name" : "Jack", "localtions" : [ "France", "Japan", "Taiwan" ] }

答案 1 :(得分:1)

您还可以在 $project 管道中使用$setUnion运算符,如下所示:

db.collection.aggregate([
    {
        "$group": {
            "_id": "$name",
            "location1": { 
               "$addToSet": "$localtion1"
            },
            "location2": { 
               "$addToSet": "$localtion2"
            }
        }
    },
    {
        "$project": {            
            "name": "$_id",
            "locations": { 
                "$setUnion": [ "$location1", "$location2" ]
            },
            "_id": 0            
        }
    }
])

会给你结果:

/* 0 */
{
    "result" : [ 
        {
            "name" : "Mary",
            "locations" : [ 
                "China", 
                "Taiwan"
            ]
        }, 
        {
            "name" : "Jack",
            "locations" : [ 
                "Japan", 
                "Taiwan", 
                "France"
            ]
        }
    ],
    "ok" : 1
}