【问题标题】:Mongoid::Criteria#last modifies the criteria and gives wrong resultsMongoid::Criteria#last 修改条件并给出错误结果
【发布时间】:2012-09-11 08:05:05
【问题描述】:

这是我使用 mongoid (3.0.0) 发现的一个有趣的模式,我怀疑这是一个错误。

1.9.3p194 :007 > products = Product.order_by([:_id, :asc ]).limit(5)
 => #<Mongoid::Criteria
   selector: {},
   options:  {:sort=>{"_id"=>1}, :limit=>5},
   class:    Product,
   embedded: false>

1.9.3p194 :008 > products.map(&:_id)
 => ["500fa5614f6d3a23d0000002", "500fa5614f6d3a23d0000003", "500fa5614f6d3a23d0000004", "500fa5614f6d3a23d0000005", "500fa5614f6d3a23d0000006"] 

到目前为止一切顺利!但是,如果我发出以下命令 - 我会得到奇怪的结果。

1.9.3p194 :012 > products.count
 => 3654017 

这向我显示所有产品数量而不是 5(因为我有 :limit => 5)

1.9.3p194 :012 > Product.count
 => 3654017 

现在更奇怪的部分:

1.9.3p194 :010 > products.last
 => #<Product _id: 504952620a5e2323460000aa, _type: nil, ... >

这应该是 _id: 500fa5614f6d3a23d0000006。现在,如果我再次尝试映射 id,我会得到:

1.9.3p194 :019 > products.map(&:id)
 => ["504952620a5e2323460000aa", "504952620a5e2323460000a9", "504952620a5e2323460000a8", "5049524f0a5e2323460000a7", "504950ab0a5e2323460000a6"] 

这完全改变了标准!但是,我得到了正确的结果:

1.9.3p194 :008 > products = Product.order_by([:_id, :asc ]).limit(5)
 => #<Mongoid::Criteria
  selector: {},
  options:  {:sort=>{"_id"=>1}, :limit=>5},
  class:    Product,
  embedded: false>

1.9.3p194 :028 > products[0].id
 => "500fa5614f6d3a23d0000002" 
1.9.3p194 :029 > products[-1].id
 => "500fa5614f6d3a23d0000006" 

这似乎与 Mongoid 3.0.0 有关。有什么想法吗?

【问题讨论】:

    标签: ruby mongodb mongoid3


    【解决方案1】:

    首先请记住,Mongoid 具有延迟加载功能:查询将在可能的最后时刻触发。

    让我们挖掘你的问题:

    • last:它将limit 设置为-1,因此它将覆盖您之前的设置。要获得您的预期行为,您必须强制 Mongoid 使用 to_a 进行查询:products = Product.order_by([:_id, :asc ]).limit(5).to_a.last

    • count:如果你想尊重limit,请使用count(true)

    【讨论】:

    • 太棒了!谢谢。 count(true) 不起作用。 p.count(true) 为 true:TrueClass 从 (mongoid-3.0.3)/lib/mongoid/contextual/mongo.rb:70:in count 抛出一个 NoMethodError: undefined method id'
    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2014-09-16
    • 2011-11-15
    • 2019-02-06
    相关资源
    最近更新 更多