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
MongoDB query to fetch array values
To fetch specific array values in MongoDB, use the find() method along with $elemMatch operator to match documents containing specific values in nested arrays.
Syntax
db.collection.find({
"arrayField": {
$elemMatch: {
"nestedField": "matchValue"
}
}
});
Sample Data
db.fetchingArrayValuesDemo.insertMany([
{
"StudentName": "David",
"StudentDetails": [
{
"FatherName": "Bob",
"CountryName": "US",
"Favourite": [
{
"Teacher": "DAVID",
"Subject": ["MySQL", "MongoDB", "Java"],
"Marks": [50, 60, 65]
}
]
}
]
},
{
"StudentName": "Robert",
"StudentDetails": [
{
"FatherName": "Sam",
"CountryName": "AUS",
"Favourite": [
{
"Teacher": "MIKE",
"Subject": ["Python", "C", "C++"],
"Marks": [76, 89, 91]
}
]
}
]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e06fc3425ddae1f53b621fa"),
ObjectId("5e06fc6825ddae1f53b621fb")
]
}
Example: Fetch Documents by Array Values
Query to find students whose favorite teacher is "DAVID" ?
db.fetchingArrayValuesDemo.find({
"StudentDetails": {
$elemMatch: {
"Favourite": {
$elemMatch: {
"Teacher": "DAVID"
}
}
}
}
});
{
"_id": ObjectId("5e06fc3425ddae1f53b621fa"),
"StudentName": "David",
"StudentDetails": [
{
"FatherName": "Bob",
"CountryName": "US",
"Favourite": [
{
"Teacher": "DAVID",
"Subject": ["MySQL", "MongoDB", "Java"],
"Marks": [50, 60, 65]
}
]
}
]
}
Key Points
-
$elemMatchmatches documents where at least one array element satisfies all specified conditions. - Use nested
$elemMatchoperators for deeply nested array structures. - Returns the entire document, not just the matching array elements.
Conclusion
The $elemMatch operator effectively queries nested arrays in MongoDB. Use multiple $elemMatch operators to navigate through deeply nested array structures and find documents containing specific array values.
Advertisements
