rjurado01
rjurado01

Reputation: 5535

Mongoid: And - Or query

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 ?

Upvotes: 14

Views: 7598

Answers (2)

Chris Heald
Chris Heald

Reputation: 62638

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])

Upvotes: 7

Kuldeep
Kuldeep

Reputation: 884

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>

Upvotes: 27

Related Questions