23tux
23tux

Reputation: 14736

Mongoid: Order by field and skip N records

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?

Upvotes: 4

Views: 5761

Answers (1)

Konstantin Rudy
Konstantin Rudy

Reputation: 2257

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.

Upvotes: 6

Related Questions