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
How do I check whether a field contains null value in MongoDB?
To check whether a field contains a null value in MongoDB, use the $type operator with type number 10 (which represents null) or compare the field directly with null.
Syntax
// Method 1: Using $type operator
db.collection.find({ fieldName: { $type: 10 } });
// Method 2: Direct null comparison
db.collection.find({ fieldName: null });
Sample Data
Let us create a collection with documents, including one with a null field ?
db.nullDemo.insertMany([
{ "FirstName": "Chris" },
{ "FirstName": null },
{ "FirstName": "Robert" }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cc68a1eac184d684e3fa270"),
ObjectId("5cc68a25ac184d684e3fa271"),
ObjectId("5cc68a2cac184d684e3fa272")
]
}
Display all documents to see the data structure ?
db.nullDemo.find();
{ "_id": ObjectId("5cc68a1eac184d684e3fa270"), "FirstName": "Chris" }
{ "_id": ObjectId("5cc68a25ac184d684e3fa271"), "FirstName": null }
{ "_id": ObjectId("5cc68a2cac184d684e3fa272"), "FirstName": "Robert" }
Method 1: Using $type Operator
Check for null values using $type: 10 ?
db.nullDemo.find({ FirstName: { $type: 10 } });
{ "_id": ObjectId("5cc68a25ac184d684e3fa271"), "FirstName": null }
Method 2: Direct Null Comparison
Alternatively, compare the field directly with null ?
db.nullDemo.find({ FirstName: null });
{ "_id": ObjectId("5cc68a25ac184d684e3fa271"), "FirstName": null }
Key Differences
-
$type: 10finds fields that are explicitly null -
fieldName: nullfinds both null values and missing fields
Conclusion
Use $type: 10 to find explicitly null fields, or fieldName: null to find both null and missing fields. The $type operator provides more precise control when checking for null values specifically.
Advertisements
