Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write "(A OR B) AND (A OR C)" queries with Mongoid?

Tags:

ruby

mongoid

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?

like image 273
Ryan Ahearn Avatar asked Oct 26 '22 05:10

Ryan Ahearn


1 Answers

(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}]})
like image 181
Chris Heald Avatar answered Nov 16 '22 17:11

Chris Heald