MongoDB inverse of query to return all items except specific documents?


To get documents except some specific documents, use $nor along with $and. Let us first create a collection with documents −

> db.demo1.insertOne({"StudentName":"Chris","StudentMarks":38});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08a4f025ddae1f53b62216")
}
> db.demo1.insertOne({"StudentName":"David","StudentMarks":78});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08a4f725ddae1f53b62217")
}
> db.demo1.insertOne({"StudentName":"Mike","StudentMarks":96});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e08a4fd25ddae1f53b62218")
}

Following is the query to display all documents from a collection with the help of find() method −

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

This will produce the following output −

{
   "_id" : ObjectId("5e08a4f025ddae1f53b62216"),
   "StudentName" : "Chris",
   "StudentMarks" : 38
}
{
   "_id" : ObjectId("5e08a4f725ddae1f53b62217"),
   "StudentName" : "David",
   "StudentMarks" : 78
}
{
   "_id" : ObjectId("5e08a4fd25ddae1f53b62218"),
   "StudentName" : "Mike",
   "StudentMarks" : 96
}

Here is the query to get inverse of query −

> db.demo1.find({$nor:[{$and:[{'StudentName':'David'},{'StudentMarks':78}]}]});

This will produce the following output. The result displays Student records with marks except 78 −

{ "_id" : ObjectId("5e08a4f025ddae1f53b62216"), "StudentName" : "Chris", "StudentMarks" : 38 }
{ "_id" : ObjectId("5e08a4fd25ddae1f53b62218"), "StudentName" : "Mike", "StudentMarks" : 96 }

Updated on: 31-Mar-2020

363 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements