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
Query a nested field within an array with MongoDB
To query a nested field within an array in MongoDB, use the $elemMatch operator to match documents where at least one array element satisfies all specified query criteria.
Syntax
db.collection.find({
"arrayField": {
"$elemMatch": {
"nestedField": "value"
}
}
});
Sample Data
Let us create a collection with documents containing nested arrays ?
db.demo153.insertMany([
{
"ClientDetails": [
{"ClientName": "Chris", "ClientProject": "Online Banking System"},
{"ClientName": "David", "ClientProject": "Online School Management"}
]
},
{
"ClientDetails": [
{"ClientName": "Carol", "ClientProject": "Online Book System"},
{"ClientName": "Mike", "ClientProject": "Game Development"}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e351957fdf09dd6d08539df"),
ObjectId("5e3519c9fdf09dd6d08539e0")
]
}
View All Documents
db.demo153.find();
{
"_id": ObjectId("5e351957fdf09dd6d08539df"),
"ClientDetails": [
{ "ClientName": "Chris", "ClientProject": "Online Banking System" },
{ "ClientName": "David", "ClientProject": "Online School Management" }
]
}
{
"_id": ObjectId("5e3519c9fdf09dd6d08539e0"),
"ClientDetails": [
{ "ClientName": "Carol", "ClientProject": "Online Book System" },
{ "ClientName": "Mike", "ClientProject": "Game Development" }
]
}
Example: Query Nested Field
Find documents where any client has the project "Online Banking System" ?
db.demo153.find({
"ClientDetails": {
"$elemMatch": {
"ClientProject": "Online Banking System"
}
}
});
{
"_id": ObjectId("5e351957fdf09dd6d08539df"),
"ClientDetails": [
{ "ClientName": "Chris", "ClientProject": "Online Banking System" },
{ "ClientName": "David", "ClientProject": "Online School Management" }
]
}
Key Points
-
$elemMatchmatches documents where at least one array element meets all specified conditions. - Use
$elemMatchfor complex queries on array elements with multiple fields. - For simple field matching, dot notation can also work:
{"ClientDetails.ClientProject": "value"}
Conclusion
The $elemMatch operator enables precise querying of nested fields within arrays, ensuring that all conditions are met within a single array element rather than across multiple elements.
Advertisements
