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
Write a MongoDB query to get nested value?
You can use dot notation to query nested values in MongoDB documents. Dot notation allows you to access fields within embedded documents using the format parentField.nestedField.
Syntax
db.collection.find({"parentField.nestedField": "value"});
Sample Data
Let us first create a collection with nested documents ?
db.nestedQueryDemo.insertMany([
{
"EmployeeName": "John",
"EmployeeDetails": {
"_id": "EMP-101",
"EmployeeAge": 23,
"EmployeeCompanyName": "IBM"
}
},
{
"EmployeeName": "Carol",
"EmployeeDetails": {
"_id": "EMP-110",
"EmployeeAge": 29,
"EmployeeCompanyName": "Amazon"
}
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c9ea31dd628fa4220163b69"),
ObjectId("5c9ea36bd628fa4220163b6a")
]
}
Display All Documents
db.nestedQueryDemo.find().pretty();
{
"_id": ObjectId("5c9ea31dd628fa4220163b69"),
"EmployeeName": "John",
"EmployeeDetails": {
"_id": "EMP-101",
"EmployeeAge": 23,
"EmployeeCompanyName": "IBM"
}
}
{
"_id": ObjectId("5c9ea36bd628fa4220163b6a"),
"EmployeeName": "Carol",
"EmployeeDetails": {
"_id": "EMP-110",
"EmployeeAge": 29,
"EmployeeCompanyName": "Amazon"
}
}
Query Nested Value
Find documents where the nested employee ID is "EMP-110" ?
db.nestedQueryDemo.find({"EmployeeDetails._id": "EMP-110"}).pretty();
{
"_id": ObjectId("5c9ea36bd628fa4220163b6a"),
"EmployeeName": "Carol",
"EmployeeDetails": {
"_id": "EMP-110",
"EmployeeAge": 29,
"EmployeeCompanyName": "Amazon"
}
}
More Examples
Query by nested age field ?
db.nestedQueryDemo.find({"EmployeeDetails.EmployeeAge": {$gt: 25}});
Query by nested company name ?
db.nestedQueryDemo.find({"EmployeeDetails.EmployeeCompanyName": "IBM"});
Conclusion
Use dot notation to access nested document fields in MongoDB queries. Simply combine the parent field name and nested field name with a dot to query embedded document values effectively.
Advertisements
