How to get a particular element from MongoDB array?

To get a particular element from a MongoDB array, use the $arrayElemAt operator within the aggregation framework. This operator allows you to extract an element at a specific index position from an array field.

Syntax

db.collection.aggregate([
    {
        $project: {
            fieldName: { $arrayElemAt: ["$arrayField", index] }
        }
    }
]);

Sample Data

db.getParticularElement.insertOne({
    "InstructorName": "Larry",
    "InstructorTechnicalSubject": ["Java", "C", "C++", "MongoDB", "MySQL", "SQL Server"]
});
{
    "acknowledged": true,
    "insertedId": ObjectId("5c7ee027559dd2396bcfbfb1")
}

Display all documents from the collection ?

db.getParticularElement.find().pretty();
{
    "_id": ObjectId("5c7ee027559dd2396bcfbfb1"),
    "InstructorName": "Larry",
    "InstructorTechnicalSubject": [
        "Java",
        "C",
        "C++",
        "MongoDB",
        "MySQL",
        "SQL Server"
    ]
}

Example: Get Element at Index 3

Extract the 4th element (index 3) from the InstructorTechnicalSubject array ?

db.getParticularElement.aggregate([
    {
        $project: {
            FourthElement: { $arrayElemAt: ["$InstructorTechnicalSubject", 3] }
        }
    }
]);
{ "_id": ObjectId("5c7ee027559dd2396bcfbfb1"), "FourthElement": "MongoDB" }

Key Points

  • Array indexing starts from 0, so index 3 represents the 4th element.
  • Use negative indices to access elements from the end: -1 for last element.
  • Returns null if the index is out of bounds.

Conclusion

The $arrayElemAt operator provides a simple way to extract specific array elements by index position. Use it within aggregation pipelines to project individual array elements as separate fields.

Updated on: 2026-03-15T00:03:39+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements