I need to write a MongoDB query of the form "A OR B OR (C AND D)" to return some records. We are using Mongoid for data access to our models.
I expanded that query to "(A OR B OR C) AND (A OR B OR D)" and was hoping that using Mongoid's Criteria method any_of
like this: Model.any_of(A, B, C).any_of(A, B, D)
would accomplish what I want, but that is expanded as "A OR B OR C OR A OR B OR D" before being sent to the database.
Is there a way to build this query, or do I have to build one query to do A OR B and another to do C AND D and take the union of them?
(Edit: I just noticed this question is 3 years old. I have no idea why it just showed up.)
You want something like this:
Model.any_of(a, b, c)
Where a
, b
, and c
are selector documents (which, remember, are ANDed with multiple clauses).
For example, if your queries are:
{a: 1}
{b: 1}
{c: 1, d: 1}
Then you would use:
Model.any_of( {a: 1}, {b: 1}, {c: 1, d: 1} )
This would generate a query like:
models.find({$or: [{a: 1}, {b: 1}, {c: 1, d: 1}]})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With