2013-04-18 58 views
11

我在mongoid 3.1.0和最新3.1.3的rails中试过类似的东西。 .limit不起作用。它下面应该返回1行,但它返回所有(4)mongoid .limit在mongoid中不起作用3.1.x

代码:

@go = Gallery.limit(1) 
logger.info "count: #{@go.count}" 

输出:

count: 4 
MOPED: 54.234.11.193:10055 QUERY database=mongohqtestdatabase collection=galleries selector= {"$query"=>{}, "$orderby"=>{:_id=>1}} flags=[:slave_ok] limit=-1 skip=0 batch_size=nil fields=nil (276.2010 

MS)

其中mongoid的版本与限制好( )?

回答

25

limit命令正常工作,但由于某种原因,count忽略了限制。如果将其转换为数组,则会看到该限制正在工作。

Array(Gallery.limit(1)).length # this gives 1 

此外,如果您实际上遍历对象,则会看到该限制正在工作。

+1

感谢。这里也是一个答案.https://github.com/mongoid/mongoid/issues/2981 – Axil 2013-04-20 02:33:38

+1

如果你觉得它有用,那么点赞答案是有礼貌的,如果它回答你的问题就接受它。 – Leopd 2013-04-20 05:42:37

14

正如官方Mongoid answer建议,我们应该使用Gallery.limit(1).count(true)

+2

@Dean你的链接已经死了 – Geoffroy 2016-05-19 20:16:01

+0

@Geoffroy修正了链接! – 2016-10-20 04:44:02

0

对于Mongoid 5改变CollectionView#count参数:

# Get a count of matching documents in the collection. 
    # 
    # @example Get the number of documents in the collection. 
    # collection_view.count 
    # 
    # @param [ Hash ] options Options for the count command. 
    # 
    # @option options :skip [ Integer ] The number of documents to skip. 
    # @option options :hint [ Hash ] Override default index selection and force 
    # MongoDB to use a specific index for the query. 
    # @option options :limit [ Integer ] Max number of docs to return. 
    # @option options :max_time_ms [ Integer ] The maximum amount of time to allow the 
    # command to run. 
    # 
    # @return [ Integer ] The document count. 
    # 
    # @since 2.0.0 

所以,你可以这样做

collection.count(limit: 1) # => 1