title: $skip and $limit in aggregation framework
body: <p>When I read the document I found the following notes:</p>
  
  <blockquote>
    <p>When a $sort immediately precedes a $limit in the pipeline, the $sort operation only maintains the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory. This optimization still applies when allowDiskUse is true and the n items exceed the aggregation memory limit.</p>
  </blockquote>
  
  <p>If I'm right about this, it applies only when I use the $sort and $limit together like</p>
  
  <pre><code>db.coll.aggregate([
      ...,
      {$sort: ...},
      {$limit: limit},
      ...
  ]);
  </code></pre>
  
  <p>However, I think most of the time we would have</p>
  
  <pre><code>db.coll.aggregate([
      ...,
      {$sort: ...},
      {$skip: skip},
      {$limit: limit},
      ...
  ]);
  </code></pre>
  
  <p><strong>Question 1</strong>: Does it mean the rule above doesn't apply if I use $skip here?</p>
  
  <p>I ask this question because theoretically MongoDB can still  calculate the top <strong>n</strong> records and  enhance performance by sorting only top <strong>n</strong> records. I didn't find any document about this though. And if the rule doesn't apply,</p>
  
  <p><strong>Question 2</strong>: Do I need to change my query to the following to enhance performance?</p>
  
  <pre><code>db.coll.aggregate([
      ...,
      {$sort: ...},
      {$limit: skip + limit},
      {$skip: skip},
      {$limit: limit},
      ...
  ]);
  </code></pre>
  
  <p><strong>EDIT</strong>: I think explains my use case would make the question above makes more sense. I'm using the text search feature provided by MongoDB 2.6 to look for products. I'm worried if the user inputs a very common key word like "red", there will be too many results returned. Thus I'm looking for better ways to generate this result.</p>
  
  <p><strong>EDIT2</strong>: It turns out that the last code above equals to </p>
  
  <pre><code>db.coll.aggregate([
      ...,
      {$sort: ...},
      {$limit: skip + limit},
      {$skip: skip},
      ...
  ]);
  </code></pre>
  
  <p>Thus I we can always use this form to make the <strong>top n</strong> rule apply.</p>