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
Find documents that contains specific field in MongoDB?
To find documents that contain a specific field in MongoDB, use the $exists operator. This operator checks whether a field exists in a document, regardless of its value.
Syntax
db.collection.find({
"fieldName": { $exists: true }
});
Sample Data
Let us create a collection with sample documents −
db.findDocumentContainsSpecificFieldDemo.insertMany([
{
"ProductPrices": {
"Product1": 10,
"Product2": 50
}
},
{
"ProductPrices": {
"Product3": 150,
"Product7": 100,
"Product5": 250
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5cf2385bb64a577be5a2bc14"),
ObjectId("5cf2387eb64a577be5a2bc15")
]
}
Display All Documents
db.findDocumentContainsSpecificFieldDemo.find().pretty();
{
"_id": ObjectId("5cf2385bb64a577be5a2bc14"),
"ProductPrices": {
"Product1": 10,
"Product2": 50
}
}
{
"_id": ObjectId("5cf2387eb64a577be5a2bc15"),
"ProductPrices": {
"Product3": 150,
"Product7": 100,
"Product5": 250
}
}
Example: Find Documents with Specific Field
To find documents that contain the field ProductPrices.Product2 −
db.findDocumentContainsSpecificFieldDemo.find({
"ProductPrices.Product2": { $exists: true }
});
{
"_id": ObjectId("5cf2385bb64a577be5a2bc14"),
"ProductPrices": {
"Product1": 10,
"Product2": 50
}
}
Key Points
- Use
$exists: trueto find documents where the field exists - Use
$exists: falseto find documents where the field does not exist - Works with nested fields using dot notation
Conclusion
The $exists operator is essential for finding documents containing specific fields. Use dot notation for nested fields and combine with other query operators for complex filtering.
Advertisements
