title: MongoDB aggregation: How to query a limited amount of "top" documents per group?
body: <p>Say I have a MongoDB collection with documents about employees:</p>
  
  <pre><code>{
    name : "John Doe",
    department : "Finance",
    salary : 100
  }
  </code></pre>
  
  <p>How can I query the X employees with the highest salaries per department?  </p>
  
  <p><strong>Edit</strong></p>
  
  <p>Just to make myself a bit more clear, this is how I thought to achieve the result:</p>
  
  <pre><code>db.collection.aggregate(
      {$sort : {salary : -1}},
      {$group : {
          _id : "$department"
          employees : {$addToSet : "$name"}
      },
      {$project : {employees : {$slice : X}}}
  )
  </code></pre>
  
  <p>But this won't work for two reasons:<br>
   1. $addToSet doesn't guarantee any ordering of the output set (at least according to the <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/addToSet/" rel="nofollow">documentation</a>).<br>
   2. <a href="https://jira.mongodb.org/browse/SERVER-6074" rel="nofollow">$slice doesn't work in the aggregation framework</a>.</p>