关于链接多个any_of标准的问题#Mongoid

Rak*_*esh 13 ruby criteria mongodb mongoid

我有一个要求,我需要运行如下所示的MongoDB查询:

db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"}], 
$or : [{"field3" : "value3"}, {"field4" : "value4"}]}) 

(field1 == value 1 or field2 == value2) and (field3 == value3 or field4 
== value4) 

我想通过标准链来实现这一点,因为查询是从代码的不同部分动态形成的.但是,如果我尝试做类似以下的事情

criteria = Collection.any_of({"field1" => "value1"}, {"field2" => 
"value2"})
criteria = criteria.any_of({"field3" => "value3"}, {"field4" => "value4"}) 

我得到结果查询,其中所有这些组合成单个$或语句,如

db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"}, 
{"field3" : "value3"}, {"field4" : "value4"}]}) 

使用标准链接实现两个"any_of"的"和"的方法是什么?

shi*_*ara 4

你可以通过避免any_of来做到这一点。

criteria = Collection.where('$or' => [{"field1" => "value1"}, {"field2" => "value2"}])
criteria = criteria.where('$or' => [{"field3" => "value3"}, {"field4" => "value4"}])
Run Code Online (Sandbox Code Playgroud)

  • 试过这个。但它也产生了相同的结果,即所有查询字段都合并到单个“$or”查询中 - 类似于使用 any_of。 (3认同)