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

北慕城南 提交于 2019-12-10 03:30:54

问题


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


回答1:


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



回答2:


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.




回答3:


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))


来源:https://stackoverflow.com/questions/20357690/rails-mongoid-model-query-result-returns-wrong-size-length-count-info-even-when

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!