Almir Filho
Almir Filho

Reputation: 4677

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

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

Upvotes: 8

Views: 1777

Answers (3)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230441

In the current version of mongoid (5.x), count(true) no longer works. Instead, count now accepts an options hash. Among them there's :limit option

criteria.count(limit: 10)

Or, to reuse whatever limit is already set on the criteria

criteria.count(criteria.options.slice(:limit))

Upvotes: 1

zpr
zpr

Reputation: 2940

As mentioned in one of the comments, in newer Mongoid versions (not sure which ones), you can simply use recipes.count(true) and this will include the limit, without needing to query the result set, as per the API here.

Upvotes: 1

mu is too short
mu is too short

Reputation: 434735

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

Upvotes: 8

Related Questions