How to query MongoDB using the $ne operator?


To query MongoDB using the $ne operator, following is the syntax −

db.yourCollectionName.find({yourFieldName:{$ne:yourValue}}).pretty();

Let us create a collection with documents −

> db.notEqaulToDemo.insertOne({"StudentName":"Larry","StudentMathMarks":68});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd3a6bde8cc557214c0ded")
}
> db.notEqaulToDemo.insertOne({"StudentName":"Chris","StudentMathMarks":88});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd3a79de8cc557214c0dee")
}
> db.notEqaulToDemo.insertOne({"StudentName":"David","StudentMathMarks":45});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd3a89de8cc557214c0def")
}
> db.notEqaulToDemo.insertOne({"StudentName":"Carol","StudentMathMarks":69});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbd3a97de8cc557214c0df0")
}

Display all documents from a collection with the help of find() method −

> db.notEqaulToDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cbd3a6bde8cc557214c0ded"),
   "StudentName" : "Larry",
   "StudentMathMarks" : 68
}
{
   "_id" : ObjectId("5cbd3a79de8cc557214c0dee"),
   "StudentName" : "Chris",
   "StudentMathMarks" : 88
}
{
   "_id" : ObjectId("5cbd3a89de8cc557214c0def"),
   "StudentName" : "David",
   "StudentMathMarks" : 45
}
{
   "_id" : ObjectId("5cbd3a97de8cc557214c0df0"),
   "StudentName" : "Carol",
   "StudentMathMarks" : 69
}

Following is the query for MongoDB $ne operator −

> db.notEqaulToDemo.find({StudentMathMarks:{$ne:88}}).pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cbd3a6bde8cc557214c0ded"),
   "StudentName" : "Larry",
   "StudentMathMarks" : 68
}
{
   "_id" : ObjectId("5cbd3a89de8cc557214c0def"),
   "StudentName" : "David",
   "StudentMathMarks" : 45
}
{
   "_id" : ObjectId("5cbd3a97de8cc557214c0df0"),
   "StudentName" : "Carol",
   "StudentMathMarks" : 69
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

81 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements