MongoDB query to implement nor query to fetch documents except a specific document


To fetch documents except a specific document, set the document to be missed using the $nor in MongoDB. Let us create a collection with documents −

> db.demo100.insertOne({"Name":"Chris","Age":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d9624b8903cdd865577c0")
}
> db.demo100.insertOne({"Name":"David","Age":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d962cb8903cdd865577c1")
}
> db.demo100.insertOne({"Name":"Bob","Age":19});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2d9634b8903cdd865577c2")
}

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

> db.demo100.find();

This will produce the following output −

{ "_id" : ObjectId("5e2d9624b8903cdd865577c0"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e2d962cb8903cdd865577c1"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e2d9634b8903cdd865577c2"), "Name" : "Bob", "Age" : 19 }

Following is the query to implement NOR query in MongoDB −

> db.demo100.find({ $nor: [ { Name:"Chris" }, { Name: { $exists: false } }, { Age: 21 }, { Age: { $exists: false } } ] } );

This will produce the following output −

{ "_id" : ObjectId("5e2d962cb8903cdd865577c1"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e2d9634b8903cdd865577c2"), "Name" : "Bob", "Age" : 19 }

Updated on: 30-Mar-2020

113 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements