これは、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 に関連しているようです。何か案は?