Find records in MongoDB that does NOT match a condition?

To find records that do not match a condition in MongoDB, use the $ne (not equal) operator. This operator excludes documents where the specified field equals the given value.

Syntax

db.collection.find({ "fieldName": { "$ne": "value" } })

Sample Data

Let us create a collection with sample documents:

db.demo148.insertMany([
    { "Message": "Hello" },
    { "Message": "Good" },
    { "Message": "Bye" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e32fb37fdf09dd6d08539c0"),
        ObjectId("5e32fb3efdf09dd6d08539c1"),
        ObjectId("5e32fb42fdf09dd6d08539c2")
    ]
}

Display all documents from the collection:

db.demo148.find()
{ "_id": ObjectId("5e32fb37fdf09dd6d08539c0"), "Message": "Hello" }
{ "_id": ObjectId("5e32fb3efdf09dd6d08539c1"), "Message": "Good" }
{ "_id": ObjectId("5e32fb42fdf09dd6d08539c2"), "Message": "Bye" }

Example: Find Records NOT Equal to "Good"

Find all documents where Message is not equal to "Good":

db.demo148.find({ "Message": { "$ne": "Good" } })
{ "_id": ObjectId("5e32fb37fdf09dd6d08539c0"), "Message": "Hello" }
{ "_id": ObjectId("5e32fb42fdf09dd6d08539c2"), "Message": "Bye" }

Key Points

  • $ne excludes documents where the field exactly matches the specified value
  • Documents with missing fields are included in results (null values don't equal the specified value)
  • Case-sensitive matching applies for string comparisons

Conclusion

The $ne operator efficiently filters out documents that match a specific condition. Use it to exclude unwanted records and find all documents that don't meet certain criteria.

Updated on: 2026-03-15T02:15:28+05:30

715 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements