Use AND and OR condition > using $and operator and $or operator in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >


Method 1 to use AND and OR condition in MongoDB >
  • using $and operator and
  • using $or operator.

First, Let's create new collection and insert document in it >
> db.employee.insert({_id : 1,  firstName:"ankit"})
> db.employee.insert({_id : 2,  firstName:"ankit", salary : 1000 })
> db.employee.insert({_id : 3,  firstName:"sam", salary : 2000 })
> db.employee.insert({_id : 4,  firstName:"neh", salary : 3000 })
First line above will create table (or collection) (if table already exists it will insert documents in it).

Find employee where
Salary =1000 and ( id = 1 or firstName = "ankit")
by using find method, $and and $or operators.


> db.employee.find({
$and : [{
salary : 1000
}, {
$or : [{
_id : 1
}, {
firstName : "ankit"
}
]
}
]
 })
Output>
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }


Method 2 to use AND and OR condition in MongoDB >
  • using $and operator and
  • using $or operator.


Find employee where
Salary = 1000 and ( id = 1 or firstName = "ankit")
by using find method, $and and $or operators.
Additionally, use $eq to find document where salary =1000


> db.employee.find({
$and : [{
salary : {$eq : 1000}
}, {
$or : [{
_id : 1
}, {
firstName : "ankit"
}
]
}
]
 })
Output>
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }



SUMMARY>
So in this mongoDB tutorial we learned how to Use AND and OR condition > using $and operator and $or operator. in mongoDB.


Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.


RELATED LINKS>

What is MongoDB - A quick introduction to database


eEdit
Must read for you :