2012-03-22 69 views
3

我遇到了与mongoid any_of问题。我试图发现有任何一个领域> 0,或另一个对象> 0.我的查询是:Mongoid或/ any_of意外行为

Model.any_of(best_friend_method.gt => 0, method.gt => 0).desc(best_friend_method, method) 

它“翻译”中:

#<Mongoid::Criteria 
    selector: {"$or"=>[{:best_friends_lc_sum=>{"$gt"=>0}, :lc_sum=>{"$gt"=>0}}]}, 
    options: {:sort=>[[:best_friends_lc_sum, :desc], [:lc_sum, :desc]]}, 
    class: FbAlbum, 
    embedded: false> 

据我了解, 这就是我要的。但它只会返回我6个结果。 Model.where(:best_friends_lc_sum.gt => 0).count也会给我6个结果,但Model.where(:lc_sum.gt => 0).count会返回我〜850个对象。

我希望我的查询返回这两个联合:是一个mongoid/mongodb错误,或者我做错了什么?

FYI:mongoid 2.4.5,MongoDB的2.0.2,3.1.3轨道

感谢您的时间!

+0

您是否正在查询正确的属性?看起来您在查询中使用了best_friend_method和method,但您的条件是best_friends_lc_sum和lc_sum。 – 2012-03-22 14:39:47

+0

是的,它是通缉。我具有相同的一组属性,但使用'lct'而不是'lc'。我的方法应该查找给出的参数,并根据那些属性(lct或lc)将用于查询的选项 – ksol 2012-03-22 14:43:20

+0

对不起ksol,没有更多信息,似乎正在构建查询通过mongoid是正确的,但我对数据模型以及这些集合中的内容感到困惑。如果你直接对mongo运行查询,它会给你你想要的吗? – 2012-03-22 15:42:22

回答

9

这是因为你只传递一个参数而不是2个参数。所以这就像你没有使用$or

尝试:

Model.any_of({best_friend_method.gt => 0}, {method.gt => 0}).desc(best_friend_method, method) 

在这种情况下,标准成为:

#<Mongoid::Criteria 
    selector: {"$or"=>[{:best_friends_lc_sum=>{"$gt"=>0}}, {:lc_sum=>{"$gt"=>0}}]}, 
    options: {:sort=>[[:best_friends_lc_sum, :desc], [:lc_sum, :desc]]}, 
    class: FbAlbum, 
    embedded: false> 

有时的{}使用是强制性的,以不同的散列分离。

+0

好的叫shingara – 2012-03-23 14:09:27

0

如果这有助于某人......在Mongoid 3中,Origin gem提供查询语法。这里是list of methods that you can use to write your Mongoid 3 queries。在这些方法中是or方法,它允许您执行$or查询:

# Mongoid query: 
Model.or(
    { name: "Martin" }, { name: "Dave" } 
) 

# resulting MongoDB query: 
{ 
    "$or" => [ 
    { "name" => "Martin" }, { "name" => "Dave" } 
    ] 
} 

使用OP的原来的例子,它可以被改写为:传递到散列

Model.or(
    { best_friend_method.gt => 0 }, 
    { method.gt => 0 } 
).order_by(
    best_friend_method, 
    method 
) 

至少一个or方法必须匹配才能返回记录。