Mongoid: Order by field and skip N records

database, mongodb, mongoid, ruby, ruby-on-rails

Solution

Let's say you have defined a model that is mapped to this collection:

class MyModel
  include Mongoid::Document

  field :user, type: String
  field :item, type: String
  field :rating, type: Integer
end

Then the queries you are looking for are quite simple:

#  I want to order by user and then within each user, I want to skip the first 10 records, and only return the other records
MyModel.asc(:user).skip(10)

#  Order by user and only return the first 10 records. If a user doesn't have 10 records, it should return for example 6 records
MyModel.asc(:user).limit(10)

Note both queries return Mongoid `Criteria` object. If you need the actual array - call `to_a` on the result.

Problem

I have a collection with the following data: ``` { "_id" : ObjectId("516b969beceaed363a000027"), "user" : "276", "item" : "796", "rating" : 1, } ``` I want to order by `user` and then within each user, I want to skip the first 10 records, and only return the other records. If a user doesn't have 10 records, it should return nothing. And I also need this the other way round: Order by user and only return the first 10 records. If a user doesn't have 10 records, it should return for example 6 records. I have no idea how to do this in Mongoid, without invoking a ruby script. Any ideas?

Original source