【问题标题】:mongoid .limit does not work in mongoid 3.1.xmongoid .limit 在 mongoid 3.1.x 中不起作用
【发布时间】:2013-04-18 04:18:55
【问题描述】:

我在带有 mongoid 3.1.0 和最新 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() ?

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

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

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

    此外,如果您实际遍历对象,您会发现限制正在发挥作用。

    【讨论】:

    • 如果您发现它有用,请点赞一个答案,如果它回答了您的问题,请接受它。
    • 这不是一个好主意,因为它会将所有文档加载到内存中,下面的 Mongoid 5 的解决方案要好得多!
    【解决方案2】:

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

    【讨论】:

    • @Dean 你的链接失效了
    • @Geoffroy 修复了链接!
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多