【问题标题】:Using a combination of ANDs and ORs in Mongoid在 Mongoid 中使用 AND 和 OR 的组合
【发布时间】:2012-10-28 23:49:54
【问题描述】:

我想构造一个表单的查询:

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 选择器只是所有字段的“$or”。这样做的正确方法是什么?谢谢。

我也很欣赏它的反面,例如 - 如何执行这个查询:

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

【问题讨论】:

    标签: syntax mongoid multiple-conditions


    【解决方案1】:

    看来我需要结合使用mongoMongoid 语法($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' } ]) 
    

    希望这可以帮助某人:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多