title: Pagination with MongoDB in Node.js (With Sorting)
body: <p>Using suggestions from <a href="https://stackoverflow.com/questions/5539955/how-to-paginate-with-mongoose-in-node-js">here</a> and <a href="http://blog.mongodirector.com/fast-paging-with-mongodb/" rel="nofollow noreferrer">here</a>, I'm trying to implement a scalable, paginating, stateless REST API in the following way:</p>
  
  <pre><code>//Page 1
  db.users.find().limit(pageSize);
  //Find the id of the last document in this page
  last_id = ...
  
  //Page 2
  users = db.users.find({'_id'&gt; last_id}).limit(pageSize);
  //Update the last id with the id of the last document in this page
  last_id = ...
  </code></pre>
  
  <p>It works in most cases, but the problem is I have to sort a list of videos according to view count and then try to paginate.</p>
  
  <pre><code>// Page 2
  videos = db.videos.find({'viewCount'&lt; last_view_count}).sort({viewCount : 'descending'}).limit(pageSize);
  </code></pre>
  
  <p>This does not work since there might be multiple items with same view count and some items will miss out when we do <code>'viewCount'&lt; last_view_count</code></p>
  
  <p>Any ideas on how to solve this problem would be appreciated :)</p>