mongodb mongoid.limit在mongoid 3.1.x中不起作用

2vuwiymt  于 2022-12-12  发布在  Go
关注(0)|答案(4)|浏览(324)

我在mongoid 3.1.0和lastest 3.1.3的rails中尝试了类似的操作。.limit不起作用。在下面它应该返回1行,但它返回了所有(4)
密码:

@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

毫秒)
mongoid哪个版本适合limit()?

gz5pxeao

gz5pxeao1#

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

bakd9h0s

bakd9h0s2#

对于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
xmq68pz9

xmq68pz93#

选择文档ID。创建一个数组,创建一个只搜索这些文档ID的查询,并一起更新它们。

ids = Model.where(foo: 'bar').only('_id').limit(1000).to_a
Model.where(:_id.in => ids).update_all(foo: 'baz')
nx7onnlm

nx7onnlm4#

limit命令可以正常工作,但是由于某种原因count忽略了这个限制。如果你将它转换成一个数组,你会看到这个限制是有效的。

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

此外,如果您实际迭代对象,您将看到限制正在起作用。

相关问题