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

To fetch documents except a specific document, use the $nor operator in MongoDB. The $nor operator performs a logical NOR operation, returning documents that do not match any of the conditions in the array.

Syntax

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

Sample Data

Let's create a collection with sample documents ?

db.demo100.insertMany([
    { "Name": "Chris", "Age": 21 },
    { "Name": "David", "Age": 23 },
    { "Name": "Bob", "Age": 19 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e2d9624b8903cdd865577c0"),
        ObjectId("5e2d962cb8903cdd865577c1"),
        ObjectId("5e2d9634b8903cdd865577c2")
    ]
}

Display All Documents

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

Example: Exclude Specific Document

Fetch all documents except the one with Name "Chris" and Age 21 ?

db.demo100.find({
    $nor: [
        { Name: "Chris" },
        { Name: { $exists: false } },
        { Age: 21 },
        { Age: { $exists: false } }
    ]
});
{ "_id": ObjectId("5e2d962cb8903cdd865577c1"), "Name": "David", "Age": 23 }
{ "_id": ObjectId("5e2d9634b8903cdd865577c2"), "Name": "Bob", "Age": 19 }

Key Points

  • $nor returns documents that fail to match all conditions in the array.
  • Including { field: { $exists: false } } ensures documents with missing fields are also excluded.
  • Use multiple conditions to precisely exclude specific documents.

Conclusion

The $nor operator effectively excludes specific documents by applying logical NOR conditions. Combine multiple field conditions to target exact documents for exclusion from query results.

Updated on: 2026-03-15T01:54:46+05:30

200 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements