Rails Mongoid model query result returns wrong size/length/count info even when using limit

count, limit, mongodb, mongoid, ruby-on-rails

Solution

From the fine manual:

- (Integer) length Also known as: size

Get's the number of documents matching the query selector.

But `.limit` doesn't really alter the query selector as it doesn't change what the query matches, `.offset` and `.limit` alter what segment of the matches are returned. This doesn't match the behavior of ActiveRecord and the documentation isn't exactly explicit about this subtle point. However, Mongoid's behaviour does match what the MongoDB shell does:

> db.things.find().limit(2).count()
23

My `things` collection contains `23` documents and you can see that the `count` ignores the `limit`.

If you want to know how many results are returned then you could `to_a` it first:

recipes.to_a.length

Problem

When querying on a certain model in my rails application, it returns the correct results, excerpt the `size`, `length` or `count` information, even using the `limit` criteria. ``` recipes = Recipe .where(:bitly_url => /some.url/) .order_by(:date => :asc) .skip(10) .limit(100) recipes.size # => 57179 recipes.count # => 57179 recipes.length # => 57179 ``` I can't understand why this is happening, it keeps showing the total count of the recipes collection, and the correct value should be 100 since I used `limit`. ``` count = 0 recipes.each do |recipe| count += 1 end # WAT count # => 100 ``` Can somebody help me? Thanks! -- Rails version: 3.2.3 Mongoid version: 2.4.10 MongoDB version: 1.8.4

Original source