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
Check for null in MongoDB?
In MongoDB, you can check for null values using the $type operator with type number 10 or alias "null". This operator specifically matches fields that contain explicit null values, not missing fields or empty strings.
Syntax
db.collection.find({"fieldName": { $type: 10 }});
// OR
db.collection.find({"fieldName": { $type: "null" }});
Sample Data
Let's create a collection with different types of values to demonstrate null checking ?
db.mongoDbEqualDemo.insertMany([
{"Age": 34},
{"Age": ""},
{"Age": null},
{"Age": 56},
{},
{"Age": null}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cd7e9121a844af18acdffa3"),
ObjectId("5cd7e9161a844af18acdffa4"),
ObjectId("5cd7e9191a844af18acdffa5"),
ObjectId("5cd7e91e1a844af18acdffa6"),
ObjectId("5cd7e9261a844af18acdffa7"),
ObjectId("5cd7e92e1a844af18acdffa8")
]
}
Example: Find Documents with Null Values
Display all documents to see the different data types ?
db.mongoDbEqualDemo.find().pretty();
{ "_id": ObjectId("5cd7e9121a844af18acdffa3"), "Age": 34 }
{ "_id": ObjectId("5cd7e9161a844af18acdffa4"), "Age": "" }
{ "_id": ObjectId("5cd7e9191a844af18acdffa5"), "Age": null }
{ "_id": ObjectId("5cd7e91e1a844af18acdffa6"), "Age": 56 }
{ "_id": ObjectId("5cd7e9261a844af18acdffa7") }
{ "_id": ObjectId("5cd7e92e1a844af18acdffa8"), "Age": null }
Now check for documents where Age field has explicit null values ?
db.mongoDbEqualDemo.find({"Age": { $type: 10 }});
{ "_id": ObjectId("5cd7e9191a844af18acdffa5"), "Age": null }
{ "_id": ObjectId("5cd7e92e1a844af18acdffa8"), "Age": null }
Key Points
-
$type: 10matches only explicit null values, not missing fields or empty strings. - You can use
$type: "null"instead of the numeric type 10 for better readability. - Missing fields and empty strings ("") are not considered null by this operator.
Conclusion
Use $type: 10 or $type: "null" to find documents with explicit null values. This approach distinguishes between null values, missing fields, and empty strings in your MongoDB queries.
Advertisements
