title: MongoDB group + sort doesn't work
body: <p>I have this situation. I have collection of posted messages. Messages can be shared (like on Facebook). Each time message is shared, a new one is created with an information about which message it's shared from, which message is the original one and the content may be altered. A single document looks like this:</p>
  
  <pre><code>{
      "_id": &lt;id&gt;
      "source": &lt;source_id&gt;   // if it's original, own id is used
      "shared_from": &lt;message_id&gt;
      "trending": 4,
      "created": &lt;Datetime&gt;
  }
  </code></pre>
  
  <p>The <code>trending</code> field tells me the 'quality' of the message.</p>
  
  <p>Now, here is the problem - I need to get some number of the best messages. I also need them to be unique by the source. Here's what I came up with and it should work (but it doesn't)</p>
  
  <pre><code>db.Messages.aggregate({
      { $sort: { trending: -1 } },
      { $group: { _id: "$source", doc_id: { $first: "$_id" } } },
      { $project: { _id: "$doc_id" } },
      { $limit: 6 }
  })
  </code></pre>
  
  <p>When I do that, I get completely messed up result. It's not sorted at all. It's just random. Am I missing anything?</p>