title: Mongo Aggregation grouping subdocument
body: <p>I'm kinda stuck doing something seemingly simple with MongoDB's aggregation framework.</p>
  
  <p>Imagine you have documents that would look like this :</p>
  
  <pre><code>[
      { a: 1, b: 2 },
      { a: 1, b: 3 },
      { a: 5, b: 6 }
  ]
  </code></pre>
  
  <ul>
  <li>How can you group documents by the field <code>a</code> and then regroup sub-documents by another field, say <code>b</code> while still calculating the total number of documents at each step ?</li>
  </ul>
  
  <p>For our example, the results would look be the following output document :</p>
  
  <pre><code>{
      results: [
          {
              _id: {
                  a: 1
              },
              sum_a: 2,
              doc_a: [
                  {
                      _id: {
                          b: 2
                      },
                      sum_b: 1
                  },
                  {
                      _id: {
                          b: 3
                      },
                      sum_b: 1
                  }
              ]
          },
          {
              _id: {
                  a: 5
              },
              sum_a: 1,
              doc_a: [
                  {
                      _id: {
                          b: 6
                      },
                      sum_b: 1
                  }
              ]
          }
      ]
  }
  </code></pre>
  
  <p>I tried things like this :</p>
  
  <pre><code>printjson(db.getSiblingDB('mydb').mycollection.aggregate([
      {
          $project: {
              a: 1,
              b: 1
          }
      },
      {
          $group: {
              _id: {
                  a: '$a'
              },
              sum_a: {
                  $sum: 1
              },
              b: {
                  $first: '$b'
              }
          }
      },
      {
          $group: {
              _id: {
                  b: '$b'
              },
              sum_b: {
                  $sum: 1
              }
          }
      },
      {
          $sort: {
              sum_a: 1
          }
      }
  ]));
  </code></pre>
  
  <p>But in the different tests I made, it keeps overwriting previous group stage results, wrongly calculating sums, ...etc.</p>
  
  <p>So I'm not really sure how to approach this problem.</p>