title: Sort and Group in one MongoDB aggregation query
body: <p>Using <code>$sort</code> and <code>$group</code> in one aggregation query behaving strangely. </p>
  
  <p>Test data:</p>
  
  <pre><code>db.createCollection("test");
  
  db.test.insert({
      ts : 100,
      category : 1
  });
  
  db.test.insert({
      ts : 80,
      category : 1
  });
  
  db.test.insert({
      ts : 60,
      category : 2
  });
  
  db.test.insert({
      ts : 40,
      category : 3
  });
  </code></pre>
  
  <p>So when sorting it by <code>ts</code> all looks good, but when I use both <code>$sort</code> and <code>$group</code> result goes in a wrong order. Query:</p>
  
  <pre><code>db.test.aggregate([
  {
      $sort : {ts: 1}
  },
  {
      $group:{"_id":"$category"}
  }
  ]);
  </code></pre>
  
  <p>And the result in reverse order:</p>
  
  <pre><code>{ "_id" : 1 }
  { "_id" : 2 }
  { "_id" : 3 }
  </code></pre>
  
  <p>Is it Mongo feature or my misunderstanding? Maby mongo firstly applied grouping and then can't sort by absent field. For this reason probably <code>mongoose</code> prohibits use distinct with sorting.</p>