I have a requirement where I need to run a MongoDB query like the following:
db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"}], $or : [{"field3" : "value3"}, {"field4" : "value4"}]})
i.e.
(field1 == value 1 or field2 == value2) and (field3 == value3 or field4 == value4)
I want to achieve this through criteria chaining because the query gets formed dynamically from different parts of the code. But if I try doing something like the following
criteria = Collection.any_of({"field1" => "value1"}, {"field2" => "value2"}) criteria = criteria.any_of({"field3" => "value3"}, {"field4" => "value4"})
I get the resultant query where all these are combined into a single $or statement like
db.collection.find({ $or : [{"field1" : "value1"}, {"field2" : "value2"}, {"field3" : "value3"}, {"field4" : "value4"}]})
What is the way to achieve "and" of the two "any_of" using criteria chaining?