title: How to use MongoDB aggregation for pagination?
body: <p>I want to perform an aggregation query that does basic pagination:</p>
  
  <ol>
  <li>Find all orders that belongs to a certain <code>company_id</code></li>
  <li>Sort the orders by <code>order_number</code></li>
  <li>Count the total number of documents</li>
  <li>Skips to e.g. document number <code>100</code> and passes on the rest</li>
  <li>Limits the number of documents to e.g. <code>2</code> and passes them on</li>
  <li>Finishes by returning the count and a selected few fields from the documents</li>
  </ol>
  
  <p>Here is a breakdown of the query:</p>
  
  <pre><code>db.Order.collection.aggregate([
  </code></pre>
  
  <p>This finds all matching documents:</p>
  
  <pre><code>  { '$match'    : { "company_id" : ObjectId("54c0...") } },
  </code></pre>
  
  <p>This sorts the documents:</p>
  
  <pre><code>  { '$sort'     : { 'order_number' : -1 } },
  </code></pre>
  
  <p>This counts the documents and passes the unmodified documents, but I'm sure doing it wrong, because things turn weird from here:</p>
  
  <pre><code>  {
      '$group' : {
        '_id'     : null,
        'count'   : { '$sum' : 1 },
        'entries' : { '$push' : "$$ROOT" }
      }
    },
  </code></pre>
  
  <p>This seems to skip some documents:</p>
  
  <pre><code>  { "$skip"     : 100 },
  </code></pre>
  
  <p>This is supposed to limit the documents, but it does not:</p>
  
  <pre><code>  { "$limit"    : 2 },
  </code></pre>
  
  <p>This does return the count, but it does not return the documents in an array, instead it returns arrays with each field:</p>
  
  <pre><code>  { '$project'  : {
        'count'     : 1,
        'entries'   : {'_id' : "$entries._id", 'order_number' : "$entries.order_number"}
      }
    }
  ])
  </code></pre>
  
  <p>This is the result:</p>
  
  <pre><code>[
    { "_id" : null,
      "count" : 300,
      "entries" : [
        {
          "_id" : [ObjectId('5a5c...'), ObjectId('5a5c...')],
          "order_number" : ["4346", "4345"]
        },
        {
          "_id" : [ObjectId('5a5c...'), ObjectId('5a5c...')],
          "order_number" : ["4346", "4345"]
        },
        ...
      ]
    }
  ]
  </code></pre>
  
  <p>Where do I get it wrong?</p>