Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select * group by in mongo aggregation

Tags:

mongodb

I am trying to do something that I think is quite simple. Suppose I have a series of records in mongo that have a common key, and variable number of attributes. I want to select all attributes and group by name across the records. For example

{ Name: George, x: 5, y: 3 }
{ Name: George, z: 9 }
{ Name: Rob, x: 12, y: 2 }

I would like to produce a CSV that looks like this:

Name     X   Y   Z
George   5   3   9
Rob      12  2

Tried

DB.data.aggregate({ $group : { _id : "$Name" } })

Unfortunately I get back all the names as records but not the union of all the possible attributes.

like image 716
Roger Sanchez Avatar asked Aug 31 '12 04:08

Roger Sanchez


1 Answers

If you want to combine the attributes, you'll need to add those to the group. For example, using $addToSet to find the unique values of the x,y,z attributes grouped by each name:

db.data.aggregate(
    { $group : {
            _id : "$Name",
            x: { $addToSet: "$x" },
            y: { $addToSet: "$y" },
            z: { $addToSet: "$z" },
    }}
)

Returns:

{
    "result" : [
        {
            "_id" : "Rob",
            "x" : [
                12
            ],
            "y" : [
                2
            ],
            "z" : [ ]
        },
        {
            "_id" : "George",
            "x" : [
                5
            ],
            "y" : [
                3
            ],
            "z" : [
                9
            ]
        }
    ],
    "ok" : 1
}
like image 90
Stennie Avatar answered Oct 07 '22 17:10

Stennie