0

I have two collections which I want to paginate through the referenced collection.

class Col1
    include Mongoid::Document

    field :slug,                :type => String
    field :created_at,          :type => DateTime

    has_many :col2,         :order => :created_at.desc
end

class Col2
    include Mongoid::Document

    field :some_id,         type: String
    field :html,                type: String
    field :created_at,          type: DateTime

    belongs_to :col1
end

And this is what I have come up with,

Col1.find_by(slug: "slug").col2.page(2).per(1).entries

My question is, is this query paginate from Mongodb and not that Mongoid will load everything and paginate from the result. So, if I have 1 million documents, it's not going to load all the documents and cache the result and paginate that? If it's going to do that, how do I paginate from Mongo db instead?

Edit:

This is the Criteria that I got from Mongoid, but I'm not sure if it's the case.

#<Mongoid::Criteria
  selector: {"_id"=>BSON::ObjectId('52d1b99465756eaf02010000')}
  options:  {:sort=>{"created_at"=>-1}, :limit=>25, :skip=>0}
  class:    Col2
  embedded: false>
toy
  • 11,711
  • 24
  • 93
  • 176
  • 1
    Mongoid/Moped is, thankfully, pretty verbose with logging its queries. Have you watched the queries to see what they're doing? – mu is too short Jan 11 '14 at 22:03
  • How do I show the query? – toy Jan 11 '14 at 22:06
  • I have edited the question to include the criteria. – toy Jan 11 '14 at 22:07
  • 2
    grep your logs for `MOPED:.*QUERY` and you should see them. The `options` in the criteria suggest that is behaving sensibly, those are options on the query to MongoDB. – mu is too short Jan 11 '14 at 22:15
  • The Criteria looks reasonable, however you'll want to make sure you have an suitable index to make the sorts efficient (see: [Use Indexes to Sort Query Results](http://docs.mongodb.org/manual/tutorial/sort-results-with-indexes/)). If the example is a common query, you'd probably want an index on `{ _id: 1, created_at: -1 }` so results are returned in sorted order. – Stennie Jan 11 '14 at 22:55

0 Answers0