title: MongoDB group by with sort and limit for each group
body: <p>For instance I have a collection:</p>
  
  <pre><code>{ "_id" : 1, "name" : "abc", "score" : 10 }
  { "_id" : 2, "name" : "abc", "score" : 15 }
  { "_id" : 3, "name" : "abc", "score" : 20 }
  { "_id" : 4, "name" : "xyz", "score" : 10 }
  { "_id" : 5, "name" : "xyz", "score" : 15 }
  { "_id" : 6, "name" : "xyz", "score" : 20 }
  </code></pre>
  
  <p>How can I do a query in Mongodb to group by <code>name</code> then sort by <code>score</code> and take it with <code>limit=2</code>. I want to get like this:</p>
  
  <pre><code>    {"_id": "abc", "items": [
            { "_id" : 3, "name" : "abc", "score" : 20 },
            { "_id" : 2, "name" : "abc", "score" : 15 }]
      }
      {"_id": "xyz", "items": [
            { "_id" : 6, "name" : "xyz", "score" : 20 },
            { "_id" : 5, "name" : "xyz", "score" : 15 }]
      }
  </code></pre>