title: How to order MongoDB Aggregation with match, sort, and limit
body: <p>My current aggregation is:</p>
  
  <pre><code>db.group_members.aggregate({
    $match: { user_id: { $in: [1,2,3] } }
  }, {
    $group: { _id: "$group_id" }
  }, {
    $sort: { last_post_at: -1 }
  }, {
    $limit: 5
  })
  </code></pre>
  
  <p>For a document structure of:</p>
  
  <pre><code>{
    _id: '...',
    user_id: '...',
    group_id: '...',
    last_post_at: Date,
  }
  </code></pre>
  
  <p>I've also got an index on <code>{user_id: 1, last_post_at: -1}</code></p>
  
  <p>Since my index is already on <code>last_post_at</code> is the sort useless? I'm not 100% sure how the ordering of this.</p>
  
  <p>My end goal is to replicate this SQL:</p>
  
  <pre><code>SELECT DISTINCT ON (group_id)
  FROM group_members
  WHERE user_id in [1,2,3]
  ORDER_BY last_post_at DESC
  LIMIT 5
  </code></pre>
  
  <p>I'm wondering how to make it performant for a very large group_members and still return it in the right order.</p>
  
  <p>UPDATE:
  I'm hoping to find a solution that will limit the number of documents loaded into memory. This will be a fairly large collection and accessed very frequently.</p>