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

  • $arrayElemAt extracts the element at the specified index from the array
  • $let defines a temporary variable to hold the extracted element
  • $expr enables the use of aggregation expressions in find queries
  • $$fst.Name accesses 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.

Updated on: 2026-03-15T01:50:16+05:30

723 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements