Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoid: And - Or query

Tags:

mongoid

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 ?

like image 916
drinor Avatar asked Jul 25 '13 08:07

drinor


People also ask

How do I query an object in MongoDB?

The find() Method To query data from MongoDB collection, you need to use MongoDB's find() method.

How do I run a MongoDB query in Robo 3T?

Open Studio 3T and connect to your MongoDB database. Next, open the Import Wizard from the toolbar. Then, choose JSON as the import format. Click OK.

What is $[] in MongoDB?

$[] The all positional operator $[] indicates that the update operator should modify all elements in the specified array field. The $[] operator has the following form: { <update operator>: { "<array>.$[]" : value } }


1 Answers

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>
like image 183
Kuldeep Avatar answered Oct 12 '22 18:10

Kuldeep