即使使用限制,Rails Mongoid模型查询结果也会返回错误的大小/长度/计数信息 [英] Rails Mongoid model query result returns wrong size/length/count info even when using limit
问题描述
在我的rails应用程序中查询某个模型时,即使使用limit
条件,它也会返回正确的结果,摘录size
,length
或count
信息.
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
我不明白为什么会这样,它一直显示食谱集合的总数,自从我使用limit
以来,正确的值应该是100.
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版本:3.2.3
Mongoid版本:2.4.10
MongoDB版本:1.8.4
--
Rails version: 3.2.3
Mongoid version: 2.4.10
MongoDB version: 1.8.4
推荐答案
摘自精细手册:
-(整数)长度
也称为:大小
- (Integer) length
Also known as: size
获取与查询选择器匹配的文档数.
Get's the number of documents matching the query selector.
但是.limit
并不会真正更改查询选择器,因为它不会更改查询匹配项,.offset
和.limit
会更改匹配的哪些段返回.这与ActiveRecord的行为不匹配,并且文档对于此微妙之处也并不十分明确.但是,Mongoid的行为确实与MongoDB Shell的行为匹配:
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
我的things
集合包含23
个文档,您可以看到count
忽略了limit
.
My things
collection contains 23
documents and you can see that the count
ignores the limit
.
如果您想知道返回了多少结果,则可以先to_a
:
If you want to know how many results are returned then you could to_a
it first:
recipes.to_a.length
这篇关于即使使用限制,Rails Mongoid模型查询结果也会返回错误的大小/长度/计数信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!