Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a combination of ANDs and ORs in Mongoid

I'd like to construct a query of the form:

select * from some_table
where 
  (field1 = 'x' or field2 = 'y') 
  and 
  (field3 = 'z' or field4 = 'w')

From reading the docs, I thought it should look something like this in Mongoid:

SomeTable.or({:field1 => 'x'}, {:field2 => 'y'})
         .and  #  or is it .intersect?
         .or({:field3 => 'z'}, {:field4 => 'w'})

But then that doesn't work - the mongo selector is simply an "$or" of all the fields. What's the correct way to do this? thanks.

I'd also appreciate the inverse of that, e.g - how to perform this query:

select * from some_table
where 
  (field1 = 'x' and field2 = 'y') 
  or
  (field3 = 'z' and field4 = 'w') 
like image 219
sa125 Avatar asked Nov 08 '12 17:11

sa125


1 Answers

It seems I needed to use a combination of mongo and Mongoid syntax (the $something operator):

SomeTable.and( :$or => [ { :field1 => 'x' }, { :field2 => 'y' } ])
         .and( :$or => [ { :field3 => 'z' }, { :field4 => 'w' } ]) 

The inverse of that is just replacing the operators:

SomeTable.or( :$and => [ { :field1 => 'x' }, { :field2 => 'y' } ])
         .or( :$and => [ { :field3 => 'z' }, { :field4 => 'w' } ]) 

Hope this helps someone :)

like image 129
sa125 Avatar answered Oct 13 '22 10:10

sa125