Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

can I use combination of OR and AND in mongodb queries?

the code below doesn't work as expected

db.things.find({ 

$and:[ 

{$or:[ 

{"first_name" : "john"}, 

{"last_name" : "john"} 

]}, 

{"phone": "12345678"} 

]});

database content:

> db.things.find(); 

"_id" : ObjectId("4fe8734ac27bc8be56947d60"), "first_name" : "john", "last_name" : "hersh", "phone" : "2222" } 

{ "_id" : ObjectId("4fe8736dc27bc8be56947d61"), "first_name" : "john", "last_name" : "hersh", "phone" : "12345678" } 

{ "_id" : ObjectId("4fe8737ec27bc8be56947d62"), "first_name" : "elton", "last_name" : "john", "phone" : "12345678" } 

{ "_id" : ObjectId("4fe8738ac27bc8be56947d63"), "first_name" : "eltonush", "last_name" : "john", "phone" : "5555" }

when querying the above query - i get nothing!

> db.things.find({$and:[{$or:[{"first_name" : "john"}, {"last_name" : "john"}]},{"phone": "12345678"}]});

>

I'm using mongo 1.8.3

2 Answers

0 votes
by (106k points)

You can use the below-mentioned code for  that:-

db.things.find({ 

$or : [ {"first_name": "john"}, 

{"last_name": "john"} 

], 

"phone": "12345678" 

})

0 votes
by (107k points)

You are trying to run the query in the older version of MongoDB. The $and operator works with MongoDB v2.0+ versions. 

For using $and/$or operator, refer to the following code:

     db.getCollection('tbl_menu_items').find({

        $and : [

            { $or : [ { price : 0.99 }, { price : 1.99 } ] },

            { $or : [ { sale : true }, { qty : { $lt : 20 } } ] }

        ]

    } )

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
asked Sep 9, 2019 in SQL by Sammy (47.6k points)
0 votes
2 answers
asked Oct 16, 2019 in Web Technology by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...