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: "f", age: 1, name: "D" },
{ gender: "m", age: 2, name: "E" },
{ gender: "f", age: 3, name: "F" },
{ gender: "m", age: 1, name: "G" },
{ gender: "f", age: 2, name: "H" },
{ gender: "m", age: 3, name: "I" },
{ gender: "f", age: 1, name: "J" }
]
I want to first group by age and secondly group by gender so that I get a nested result looking something like
[{
_id: "1",
children: [
{ _id: "f" },
{ _id: "m" }
]
}, {
_id: "2",
children: [
{ _id: "f" },
{ _id: "m" }
]
}, {
_id: "3",
children: [
{ _id: "f" },
{ _id: "m" }
]
}]
Here is what I tried so far:
db.example.aggregate(
{ $group: { _id: "$age", children: { $addToSet: {
age: "$age", gender: "$gender", name: "$name"
}}}},
{ $group: { _id: "$children.gender"}}
)
But this returns an {_id: null}
as its result. Is this possible and in case yes, how?