0

这是我使用 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 有关。有任何想法吗?

4

1 回答 1

1

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

让我们挖掘您的问题:

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

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

于 2012-09-11T08:32:07.867 回答