Mongoid: And - Or query
Asked Answered
A

2

14

I have this query:

User.or( { name: 'John' }, { name: 'Sara' } ).or( { age: 17 }, { age: 18 } ) )

It returns the next Criteria:

#<Mongoid::Criteria
  selector: {"enabled"=>true, "$or"=>[{"name"=>"John"}, {"name"=>"Anoun"}, {"age"=>17}. {"age"=>18}]}
  options:  {}
  class:    User
  embedded: false>

But I want to do 'and' betweend two 'or' that return something like this:

#<Mongoid::Criteria
  selector: {"enabled"=>true, "$and"=>[
    {"$or"=>[{"name"=>"John"}, {"name"=>"Anoun"}]}, 
    {"$or"=>[{"age"=>17}, {"age"=>18}]}
  ] }
  options:  {}
  class:    User
  embedded: false>

How would be the query ?

Atheling answered 25/7, 2013 at 8:30 Comment(0)
S
27

this might help you,

User.where(enabled: true)
    .and( 
          User.or( { name: 'John' }, { name: 'Sara' } ).selector,
          User.or( { age: 17 }, { age: 18 } ).selector
        )

this will return:

#<Mongoid::Criteria
  selector: {"enabled"=>true, "$and"=>[{"$or"=>[{"name"=>"John"}, {"name"=>"Sara"}]}, {"$or"=>[{"age"=>17}, {"age"=>18}]}]}
  options:  {}
  class:    User
  embedded: false>
Sienkiewicz answered 28/7, 2013 at 4:40 Comment(0)
T
7

You don't need chained $or queries here - you just want documents where the name is in a list, and where the age is in a list. Mongo provides this easily:

db.users.find({enabled: true, name: {$in: ["John", "Sara"]}, age: {$in: [17, 18]}})

In Mongoid parlance, this is simply:

User.where(enabled: true, name.in: ["John", "Sara"], age.in: [17, 18])
Tortuga answered 28/7, 2013 at 6:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.