title: Efficient pagination of MongoDB aggregation?
body: <p>For efficiency, the Mongo documentation recommends that limit statements immediately follow sort statements, thus ending up with the somewhat nonsensical:</p>
  
  <pre><code> collection.find(f).sort(s).limit(l).skip(p)
  </code></pre>
  
  <p>I say this is somewhat nonsensical because it seems to say take the first l items, and then drop the first p of those l.   Since p is usually larger than l, you'd think you'd end up with no results, but in practice you end up with l results.</p>
  
  <p>Aggregation works more as you'd expect:</p>
  
  <pre><code>collection.aggregate({$unwind: u}, {$group: g},{$match: f}, {$sort: s}, {$limit: l}, {$skip: p})
  </code></pre>
  
  <p>returns 0 results if p>=l.</p>
  
  <pre><code>collection.aggregate({$unwind: u}, {$group: g}, {$match: f}, {$sort: s}, {$skip: p}, {$limit: l})
  </code></pre>
  
  <p>works, but the documentation seems to imply that this will fail if the match returns a result set that's larger than working memory.    Is this true?   If so, is there a better way to perform pagination on a result set returned through aggregation?</p>
  
  <p>Source:  the "Changed in version 2.4" comment at the end of this page:  <a href="http://docs.mongodb.org/manual/reference/operator/aggregation/sort/" rel="noreferrer">http://docs.mongodb.org/manual/reference/operator/aggregation/sort/</a></p>