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 on nth element (variable index) of subdocument array
To query the nth element (variable index) of a subdocument array in MongoDB, use $expr with $let to define a temporary variable that extracts the element at a specific index using $arrayElemAt.
Syntax
db.collection.find({
$expr: {
$let: {
vars: { variableName: { $arrayElemAt: [ "$arrayField", index ] } },
in: { $eq: [ "$$variableName.field", "value" ] }
}
}
})
Sample Data
db.demo72.insertOne({
"StudentDetails": [
{
"Name": "Chris",
"Age": 21
},
{
"Name": "David",
"Age": 23
},
{
"Name": "Bob",
"Age": 20
}
]
});
{
"acknowledged": true,
"insertedId": ObjectId("5e29b4ad71bf0181ecc42269")
}
Display All Documents
db.demo72.find().pretty();
{
"_id": ObjectId("5e29b4ad71bf0181ecc42269"),
"StudentDetails": [
{
"Name": "Chris",
"Age": 21
},
{
"Name": "David",
"Age": 23
},
{
"Name": "Bob",
"Age": 20
}
]
}
Example: Query Element at Index 1
Find documents where the student at index 1 (second position) has the name "David" :
db.demo72.find({
$expr: {
$let: {
vars: { fst: { $arrayElemAt: [ "$StudentDetails", 1 ] } },
in: { $eq: [ "$$fst.Name", "David" ] }
}
}
})
{
"_id": ObjectId("5e29b4ad71bf0181ecc42269"),
"StudentDetails": [
{ "Name": "Chris", "Age": 21 },
{ "Name": "David", "Age": 23 },
{ "Name": "Bob", "Age": 20 }
]
}
How It Works
-
$arrayElemAtextracts the element at the specified index from the array -
$letdefines a temporary variable to hold the extracted element -
$exprenables the use of aggregation expressions in find queries -
$$fst.Nameaccesses the Name field of the extracted element
Conclusion
Use $expr with $let and $arrayElemAt to query specific array elements by index. This approach allows you to match documents based on fields within array elements at any position.
Advertisements
