How to query with nand operator in MongoDB?

MongoDB doesn't have a $nand operator, but you can achieve NAND (Not AND) logic by using $or with $ne operators. This returns documents where at least one condition is false.

Syntax

db.collection.find({
    $or: [
        { "field1": { $ne: value1 } },
        { "field2": { $ne: value2 } }
    ]
});

Sample Data

db.demo266.insertMany([
    { "active1": true, "active2": false },
    { "active1": true, "active2": true },
    { "active1": false, "active2": false },
    { "active1": false, "active2": true }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e480f4b1627c0c63e7dbaa7"),
        ObjectId("5e480f501627c0c63e7dbaa8"),
        ObjectId("5e480f561627c0c63e7dbaa9"),
        ObjectId("5e480f701627c0c63e7dbaaa")
    ]
}

Display All Documents

db.demo266.find();
{ "_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 }

Example: NAND Query

Find documents where NOT (active1=true AND active2=true) using $or with $ne ?

db.demo266.find({
    $or: [
        { "active1": { $ne: true } },
        { "active2": { $ne: true } }
    ]
});
{ "_id": ObjectId("5e480f4b1627c0c63e7dbaa7"), "active1": true, "active2": false }
{ "_id": ObjectId("5e480f561627c0c63e7dbaa9"), "active1": false, "active2": false }
{ "_id": ObjectId("5e480f701627c0c63e7dbaaa"), "active1": false, "active2": true }

How It Works

The query returns documents where at least one field is not true:

  • Document 1: active1=true, active2=false (matches because active2 ? true)
  • Document 3: active1=false, active2=false (matches because both ? true)
  • Document 4: active1=false, active2=true (matches because active1 ? true)

Only the document with both fields true is excluded.

Conclusion

Use $or with $ne operators to implement NAND logic in MongoDB. This pattern returns documents where at least one condition is false, effectively inverting AND logic.

Updated on: 2026-03-15T02:10:21+05:30

309 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements