EQUALS (=) and NOT EQUALS (!=) conditions - using $where, $eq and $ne operator in MongoDB

You are here : Home / MongoDB Tutorial


Contents of page >

EQUALS (=) and NOT EQUALS (!=) conditions - using  $where, $eq and $ne operator in MongoDB

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


1) EQUALS (=) - using $eq operator.
Find employee where
Salary = 2000
by using find method and $eq operator.


> db.employee.find( { salary : {$eq : 2000} } )
Output>
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }


2) NOT EQUALS (!=) - using $ne operator.
Find employee where
Salary != 2000
by using find method and $ne operator.


> db.employee.find( { salary : {$ne : 2000} } )
Output>
{ "_id" : 1, "firstName" : "ankit" }
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 4, "firstName" : "neh", "salary" : 3000 }


3) EQUALS (=) - using $where operator.
Find employee where
Salary = 2000
by using find method and $where operator.


> db.employee.find({  $where:"this.salary == 2000"})
Output>
{ "_id" : 3, "firstName" : "sam", "salary" : 2000 }


4) NOT EQUALS (!=) - using $where operator.
Find employee where
Salary != 2000
by using find method and $where operator.


> db.employee.find({  $where:"this.salary != 2000"})
Output>
{ "_id" : 1, "firstName" : "ankit" }
{ "_id" : 2, "firstName" : "ankit", "salary" : 1000 }
{ "_id" : 4, "firstName" : "neh", "salary" : 3000 }




5) SUMMARY>
So in this mongoDB tutorial we learned how to use EQUALS (=) and NOT EQUALS (!=) conditions - using  $where, $eq and $ne operator in MongoDB.


1) EQUALS (=) - using $eq operator.
Find employee where
Salary = 2000
> db.employee.find( { salary : {$eq : 2000} } )


2) NOT EQUALS (!=) - using $ne operator.
Find employee where
Salary != 2000
> db.employee.find( { salary : {$ne : 2000} } )


3) EQUALS (=) - using $where operator.
Find employee where
Salary = 2000
> db.employee.find({  $where:"this.salary == 2000"})


4) NOT EQUALS (!=) - using $where operator.
Find employee where
Salary != 2000
> db.employee.find({  $where:"this.salary != 2000"})

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 :