title: MongoDB: using limit and skip on complex sort order in either direction
body: <p>I have a complex sort order using several fields. The 'entry object' is the first item in the first batch defined by a query. I'm trying to create an infinite scroller where the entry item is shown at the top--scrolling down works as expected and scrolling up show items previous to the entry item.</p>
  
  <p>Using a simple sort on a unique field like "username" is pretty easy but in my case the sort takes at least three fields in order to produce a unique ordering. </p>
  
  <p>Reversing the sort order is not a problem either.</p>
  
  <p>The question is how to define the entry object and get items both after and before it in the sorted collection using skip and limit. A negative value for skip is not allowed afaik.</p>
  
  <p>Using mongoid and Rails the sort is defined by:</p>
  
  <pre><code>scope :rating_watchable, order_by(avg_rating: :desc, release_date: :desc, title: :asc)
  </code></pre>
  
  <p>The first object returned from the following is the 'entry object' at position 0:</p>
  
  <pre><code>Object.rating_watchable.where(:avg_rating.gte =&gt; 3).skip(0).limit(BATCH_SIZE)
  </code></pre>
  
  <p>This last query returns objects correctly and if I reverse the sort order I can get objects in the correct order but I can't think of how to define the same entry object using a relative  "where" clause. I need this to get the skip/limit to work right in reverse order.</p>
  
  <p>Sure would be nice to have a negative skip like this:</p>
  
  <pre><code>Object.rating_watchable.where(:avg_rating.gte =&gt; 3).skip( -BATCH_SIZE * batch_num ).limit(BATCH_SIZE)
  </code></pre>
  
  <p>maybe I'm missing some better way to do this?</p>