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
MongoDB query which represents not equal to null or empty?
To set a query for not equal to null or empty, use the $nin operator. This operator selects documents where the field value is not in the specified array of values, effectively filtering out null and empty string values.
Syntax
db.yourCollectionName.find({yourFieldName: {$nin: [null, ""]}});
Sample Data
db.notEqualToNullOrEmptyDemo.insertMany([
{"UserName": "Larry", "UserAge": 24},
{"UserName": "", "UserAge": 29},
{"UserName": "Sam", "UserAge": 32},
{"UserName": null, "UserAge": 27},
{"UserName": "Robert", "UserAge": 26},
{"UserName": "", "UserAge": 23}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9d20b6a629b87623db1b26"),
ObjectId("5c9d20bea629b87623db1b27"),
ObjectId("5c9d20c7a629b87623db1b28"),
ObjectId("5c9d20d2a629b87623db1b29"),
ObjectId("5c9d20dda629b87623db1b2a"),
ObjectId("5c9d20e7a629b87623db1b2b")
]
}
Example: Filter Non-Null and Non-Empty Values
Query to find all documents where UserName is neither null nor empty ?
db.notEqualToNullOrEmptyDemo.find({UserName: {$nin: [null, ""]}});
{
"_id": ObjectId("5c9d20b6a629b87623db1b26"),
"UserName": "Larry",
"UserAge": 24
}
{
"_id": ObjectId("5c9d20c7a629b87623db1b28"),
"UserName": "Sam",
"UserAge": 32
}
{
"_id": ObjectId("5c9d20dda629b87623db1b2a"),
"UserName": "Robert",
"UserAge": 26
}
Key Points
-
$nin(not in) excludes documents where the field matches any value in the array. - The array
[null, ""]filters out both null values and empty strings. - Only documents with actual string values will be returned.
Conclusion
Use $nin with [null, ""] to effectively query for fields that are not null or empty. This operator provides a clean way to filter out unwanted null and empty string values from your results.
Advertisements
