How to query with nand operator in MongoDB?


The $not operator won’t invert a complex expression. Therefore, use $and or $or with $ne operator.

Let us create a collection with documents −

> db.demo266.insertOne({"active1":true,"active2":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e480f4b1627c0c63e7dbaa7")
}
> db.demo266.insertOne({"active1":true,"active2":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e480f501627c0c63e7dbaa8")
}
> db.demo266.insertOne({"active1":false,"active2":false});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e480f561627c0c63e7dbaa9")
}
> db.demo266.insertOne({"active1":false,"active2":true});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e480f701627c0c63e7dbaaa")
}

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

> db.demo266.find();

This will produce the following output −

{ "_id" : ObjectId("5e480f4b1627c0c63e7dbaa7"), "active1" : true, "active2" : false }
{ "_id" : ObjectId("5e480f501627c0c63e7dbaa8"), "active1" : true, "active2" : true }
{ "_id" : ObjectId("5e480f561627c0c63e7dbaa9"), "active1" : false, "active2" : false }
{ "_id" : ObjectId("5e480f701627c0c63e7dbaaa"), "active1" : false, "active2" : true }

Following is the query to use $or with $ne operator −

> db.demo266.find({$or:[{"active1":{"$ne":true}},{"active2":{"$ne":true}}]});

This will produce the following output −

{ "_id" : ObjectId("5e480f4b1627c0c63e7dbaa7"), "active1" : true, "active2" : false }
{ "_id" : ObjectId("5e480f561627c0c63e7dbaa9"), "active1" : false, "active2" : false }
{ "_id" : ObjectId("5e480f701627c0c63e7dbaaa"), "active1" : false, "active2" : true }

Updated on: 31-Mar-2020

163 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements