Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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: nullexcludes documents where the field is null or undefined. - MongoDB treats
undefinedvalues the same asnullwhen 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.
Advertisements
