19

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?

0

1 Answer 1

54

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", 
Sign up to request clarification or add additional context in comments.

1 Comment

I was looking for this, as I failed all the time trying to recreate, but one more question how to I count the gender? How many times a gender appears for every age?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.