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 the document by field name with a specific value in MongoDB?
To find documents by field name with a specific value in MongoDB, you can use the $exists operator to check if a field exists, or use dot notation to match specific field values in nested documents.
Syntax
// Check if field exists
db.collection.find({"fieldName": {$exists: true}})
// Find by specific value in nested field
db.collection.find({"parent.child": "specificValue"})
Sample Data
db.findByFieldName.insertMany([
{
"Client": {
"ClientDetails": {
"ClientName": "Larry",
"ClientAge": 29
},
"ClientProjectDetails": {
"ProjectName": "Online Book Store",
"TeamSize": 10,
"TechnologyUsed": "Spring Boot"
}
}
},
{
"Client": {
"ClientDetails": {
"ClientName": "Chris",
"ClientAge": 27
},
"ClientEducationDetails": {
"isEducated": true,
"CollegeName": "M.I.T."
}
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("..."),
ObjectId("...")
]
}
Example 1: Find Documents Where Field Exists
Find all documents that have the "ClientProjectDetails" field ?
db.findByFieldName.find({"Client.ClientProjectDetails": {$exists: true}});
{
"_id": ObjectId("5c9e93b2d628fa4220163b64"),
"Client": {
"ClientDetails": {
"ClientName": "Larry",
"ClientAge": 29
},
"ClientProjectDetails": {
"ProjectName": "Online Book Store",
"TeamSize": 10,
"TechnologyUsed": "Spring Boot"
}
}
}
Example 2: Find by Specific Field Value
Find documents where ClientName is "Chris" ?
db.findByFieldName.find({"Client.ClientDetails.ClientName": "Chris"});
{
"_id": ObjectId("5c9e9421d628fa4220163b65"),
"Client": {
"ClientDetails": {
"ClientName": "Chris",
"ClientAge": 27
},
"ClientEducationDetails": {
"isEducated": true,
"CollegeName": "M.I.T."
}
}
}
Key Points
-
$exists: truefinds documents where the specified field exists -
$exists: falsefinds documents where the field does not exist - Use dot notation to access nested fields:
"parent.child.field"
Conclusion
Use $exists to find documents by field presence, or dot notation with specific values to match nested field content. Both approaches help filter documents based on field structure and values.
Advertisements
