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 to find if element exists in document - MongoDB?
To find if an element exists in a MongoDB document, use the $exists operator. This operator checks whether a specified field is present in the document, regardless of its value.
Syntax
db.collection.find({"fieldName": {$exists: true}});
db.collection.find({"fieldName": {$exists: false}});
Sample Data
db.demo497.insertMany([
{"details": [{"Name": "Chris"}, {"Name": "Bob"}]},
{"details": [{"Name": "Carol"}]},
{"details": [{}]}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e84b3cfb0f3fa88e22790d1"),
ObjectId("5e84b3d9b0f3fa88e22790d2"),
ObjectId("5e84b3e9b0f3fa88e22790d3")
]
}
Display all documents from the collection ?
db.demo497.find();
{ "_id": ObjectId("5e84b3cfb0f3fa88e22790d1"), "details": [{"Name": "Chris"}, {"Name": "Bob"}] }
{ "_id": ObjectId("5e84b3d9b0f3fa88e22790d2"), "details": [{"Name": "Carol"}] }
{ "_id": ObjectId("5e84b3e9b0f3fa88e22790d3"), "details": [{}] }
Example: Check if Name Field Exists
Find documents where the Name field exists within the details array ?
db.demo497.find({"details.Name": {$exists: true}});
{ "_id": ObjectId("5e84b3cfb0f3fa88e22790d1"), "details": [{"Name": "Chris"}, {"Name": "Bob"}] }
{ "_id": ObjectId("5e84b3d9b0f3fa88e22790d2"), "details": [{"Name": "Carol"}] }
Example: Using $or with $exists
Find documents where either the Name field is not "Carol" or the details field doesn't exist ?
db.demo497.find({
$or: [
{"details.Name": {$ne: "Carol"}},
{"details": {$exists: false}}
]
});
{ "_id": ObjectId("5e84b3cfb0f3fa88e22790d1"), "details": [{"Name": "Chris"}, {"Name": "Bob"}] }
{ "_id": ObjectId("5e84b3e9b0f3fa88e22790d3"), "details": [{}] }
Key Points
-
$exists: truereturns documents where the field is present -
$exists: falsereturns documents where the field is absent - Works with nested fields using dot notation
Conclusion
The $exists operator is essential for checking field presence in MongoDB documents. Combine it with $or, $ne, and other operators for complex existence-based queries.
Advertisements
