Last Updated: February 25, 2016
·
1.174K
· agripinoduarte

Using $ne operator in MongoDB queries

When querying a collection in MongoDB, equality and inequality queries works in different ways. For example:

db.users.insert({age: 31})

the query

db.users.find({age:31})

outputs

{ "_id" : ObjectId("52e277236c87469f736be017"), "age" : 31 }

But, when we are looking for a register that can have a certain field, the $ne operator will also consider the existence of the field. So, the query

db.users.find({active: {$ne: true}})

outputs

{ "_id" : ObjectId("52e277236c87469f736be017"), "age" : 31 }

which means it will return all registers where the the value of 'active' is not 'true', which is true for the object that only has the field age:31.