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

MongoDBDatabaseBig Data Analytics

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 }
raja
Published on 30-Mar-2020 11:23:56
Advertisements