title: MongoDB Group by field, count it and sort it desc
body: <p>I have the following document structure:</p>
  
  <pre><code>{
      ..
      "mainsubject" : {
          "code": 2768,
          "name": "Abc"
      }
  }
  </code></pre>
  
  <p>Now I need a list of all mainsubject.code's and how often they are used. </p>
  
  <p>In SQL i would do something like this:</p>
  
  <pre><code>SELECT mainsubject_code, COUNT(*) AS 'count'
  FROM products
  GROUP BY mainsubject_code
  ORDER BY count
  </code></pre>
  
  <p>I already was able to group it and count it:</p>
  
  <pre><code>db.products.aggregate([
      {"$group" : {_id:"$mainsubject.code", count:{$sum:1}}}
  ]);
  </code></pre>
  
  <p>But how to sort it?</p>
  
  <pre><code>db.coll.aggregate([
    {
       $group: { 
          _id: "$mainsubject.code", 
          countA: { $sum: 1}
       }
    },
    {
      $sort:{$mainsubject.code:1}
    }
  ])
  </code></pre>
  
  <p>did not work?</p>