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
Implementing MongoDB exists and ne?
The $exists operator checks whether a field exists in a document, while $ne (not equal) filters documents where a field value does not match the specified value. Combining both operators helps find documents with existing fields that contain meaningful data.
Syntax
// $exists operator
db.collection.find({ "fieldName": { "$exists": true/false } });
// $ne operator
db.collection.find({ "fieldName": { "$ne": "value" } });
// Combined usage
db.collection.find({
"$and": [
{ "fieldName": { "$exists": true } },
{ "fieldName": { "$ne": "unwantedValue" } }
]
});
Sample Data
db.existsDemo.insertMany([
{ "Name": "Chris", "Age": 21 },
{ "Name": "", "Age": null },
{ "Name": null, "Age": 24 },
{ "Age": 23 }
]);
Display All Documents
db.existsDemo.find().pretty();
{
"_id" : ObjectId("5cd7c3916d78f205348bc650"),
"Name" : "Chris",
"Age" : 21
}
{ "_id" : ObjectId("5cd7c39a6d78f205348bc651"), "Name" : "", "Age" : null }
{ "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }
{ "_id" : ObjectId("5cd7c3c36d78f205348bc653"), "Age" : 23 }
Example: Find Documents with Non-Empty Name Field
Find documents where the "Name" field exists and is not an empty string ?
db.existsDemo.find({
"$and": [
{ "Name": { "$exists": true } },
{ "Name": { "$ne": "" } }
]
});
{ "_id" : ObjectId("5cd7c3916d78f205348bc650"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5cd7c3a66d78f205348bc652"), "Name" : null, "Age" : 24 }
Key Points
-
$exists: truematches documents where the field is present, even if the value isnull -
$exists: falsematches documents where the field is completely missing -
$nematches all values except the specified one, includingnull - Combining both operators helps filter for fields with meaningful non-empty values
Conclusion
Use $exists and $ne together to find documents with existing fields that contain meaningful data. This combination is particularly useful for filtering out empty strings, null values, or missing fields in query results.
Advertisements
