title: mongodb aggregation sort
body: <p>I have a database of students and their contact details.
  I'm trying to find out the postcode that houses the most students.
  The documents for the students look something like this...</p>
  
  <blockquote>
    <p>{studentcode: 'smi0001', firstname: 'bob', surname: 'smith', postcode:
    2001}</p>
  </blockquote>
  
  <p>I thought I could use the aggregation framework to find out the postcode with the most students by doing something like...</p>
  
  <pre><code>db.students.aggregate({$project: { postcode: 1 }, $group: {_id: '$postcode', students: {$sum: 1}}})
  </code></pre>
  
  <p>this works as expected (returns postcodes as <code>_id</code> and the number of students in each postcode as 'students', but if I add <code>$sort</code> to the pipeline it seems to try sorting by the whole student collection instead of the results of the <code>$group</code> operation.</p>
  
  <p>what I'm trying look like...</p>
  
  <pre><code>db.students.aggregate({$project: { postcode: 1 }, $group: {_id: '$postcode', students: {$sum: 1}}, $sort: {_id: -1}})
  </code></pre>
  
  <p>but it returns the whole collection and disregards the <code>$project</code> and <code>$group</code>...
  Am I missing something? I thought I'd just be able to sort by descending number of students and return the first item.
  Thanks in advance for any help.</p>