我想构建一个表单查询:
select * from some_table
where
(field1 = 'x' or field2 = 'y')
and
(field3 = 'z' or field4 = 'w')
通过阅读文档,我认为它应该在Mongoid
中看起来像这样:
SomeTable.or({:field1 => 'x'}, {:field2 => 'y'})
.and # or is it .intersect?
.or({:field3 => 'z'}, {:field4 => 'w'})
但是那不起作用 - mongo选择器只是所有字段中的“$或”。这样做的正确方法是什么?感谢。
我也很欣赏它的反面,例如 - 如何执行此查询:
select * from some_table
where
(field1 = 'x' and field2 = 'y')
or
(field3 = 'z' and field4 = 'w')
答案 0 :(得分:5)
我似乎需要使用mongo
和Mongoid
语法($something
运算符)的组合:
SomeTable.and( :$or => [ { :field1 => 'x' }, { :field2 => 'y' } ])
.and( :$or => [ { :field3 => 'z' }, { :field4 => 'w' } ])
反过来就是替换运算符:
SomeTable.or( :$and => [ { :field1 => 'x' }, { :field2 => 'y' } ])
.or( :$and => [ { :field3 => 'z' }, { :field4 => 'w' } ])
希望这有助于某人:)