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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With