Given a database the form of
[
{ gender: \"m\", age: 1, name: \"A\" },
{ gender: \"f\", age: 2, name: \"B\" },
{ gender: \"m\", age: 3, name: \"C\" },
{ gender:
Something like this should do it;
db.example.aggregate(
{
$group: {
_id: { age: "$age", gender: "$gender" },
names: { $addToSet: "$name" }
}
},
{
$group: {
_id: { age: "$_id.age" },
children: { $addToSet: { gender: "$_id.gender", names:"$names" } }
}
}
)
...which gives the result;
{
"_id" : {
"age" : 1
},
"children" : [
{ "gender" : "m", "names" : [ "G", "A" ] },
{ "gender" : "f", "names" : [ "J", "D" ] }
]
},
...
If you want the age as _id
as in your example, just replace the second grouping's _id
by;
_id: "$_id.age",