title: Nested grouping with MongoDB
body: <p>Given a database the form of</p>
  
  <pre><code>[
  { 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" }
  ]
  </code></pre>
  
  <p>I want to first group by age and secondly group by gender so that I get a nested result looking something like</p>
  
  <pre><code>[{
      _id: "1",
      children: [
          { _id: "f" },
          { _id: "m" }
      ]
  }, {
      _id: "2",
      children: [
          { _id: "f" },
          { _id: "m" }
      ]
  }, {
      _id: "3",
      children: [
          { _id: "f" },
          { _id: "m" }
      ]
  }]
  </code></pre>
  
  <p>Here is what I tried so far:</p>
  
  <pre><code>db.example.aggregate(
  { $group: { _id: "$age", children: { $addToSet: {
      age: "$age", gender: "$gender", name: "$name"
  }}}},
  { $group: { _id: "$children.gender"}}
  )
  </code></pre>
  
  <p>But this returns an <code>{_id: null}</code> as its result. Is this possible and in case yes, how?</p>