Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push multiple columns' value within group

It seems my query will won't act as my expect

I want to group by name and mapping location1 and location2 into an array called locations

Data

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

Expected result

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

Query

db.collection.aggregate([
    {
        $group: {
            _id: "$name",
            "localtions":{
                $addToSet: "$localtion1"
            },
            "localtions":{
                $addToSet: "$localtion2"
            }            
            count: { $sum: 1 }
        }
    },
    {
        $project: {
            name: "$_id",
            localtions: "$localtions",
            _id: 0
        }
    },    
])
like image 456
newBike Avatar asked Apr 08 '15 09:04

newBike


1 Answers

You can use the $setUnion operator. For others set operators read this.

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

Output

{ "name" : "Mary", "localtions" : [ "Taiwan", "China" ] }
{ "name" : "Jack", "localtions" : [ "France", "Japan", "Taiwan" ] }
like image 69
styvane Avatar answered Oct 19 '22 23:10

styvane