Ignore NULL and UNDEFINED values while running a MongoDB query

To ignore NULL and UNDEFINED values while querying in MongoDB, use the $ne (not equal) operator. This operator excludes documents where the specified field is null or undefined.

Syntax

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

Create Sample Data

db.demo35.insertMany([
    {"Name": "Chris"},
    {"Name": null},
    {"Name": "Bob"},
    {"Name": undefined}
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e175e42cfb11e5c34d898d0"),
        ObjectId("5e175e46cfb11e5c34d898d1"),
        ObjectId("5e175e4bcfb11e5c34d898d2"),
        ObjectId("5e175e54cfb11e5c34d898d3")
    ]
}

Display All Documents

db.demo35.find();
{ "_id": ObjectId("5e175e42cfb11e5c34d898d0"), "Name": "Chris" }
{ "_id": ObjectId("5e175e46cfb11e5c34d898d1"), "Name": null }
{ "_id": ObjectId("5e175e4bcfb11e5c34d898d2"), "Name": "Bob" }
{ "_id": ObjectId("5e175e54cfb11e5c34d898d3"), "Name": undefined }

Ignore NULL and UNDEFINED Values

db.demo35.find({"Name": {$ne: null}});
{ "_id": ObjectId("5e175e42cfb11e5c34d898d0"), "Name": "Chris" }
{ "_id": ObjectId("5e175e4bcfb11e5c34d898d2"), "Name": "Bob" }

Key Points

  • $ne: null excludes documents where the field is null or undefined.
  • MongoDB treats undefined values the same as null when using $ne.
  • Documents without the specified field are also excluded from results.

Conclusion

Use $ne: null to filter out documents with NULL or UNDEFINED values. This operator effectively excludes both null values and undefined values in a single query condition.

Updated on: 2026-03-15T02:41:02+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements