MongoDB $arrayElemAt Operator (original) (raw)

Last Updated : 15 Apr, 2026

The $arrayElemAt operator retrieves a specific element from an array by index and is commonly used in aggregation pipelines to extract targeted values efficiently.

Syntax

{ $arrayElemAt: [ , ] }

Features of $arrayElemAt Operator

Here are some features:

Examples of MongoDB $arrayElemAt

In the following examples, we are working with:

**Database: GeeksforGeeks
**Collection: arrayExample
**Document: Three documents that contain the details in the form of field-value pairs.

Screenshot-2026-02-13-120016

Example 1: Retrieving First and Last Items

Find the elements of the array(i.e., the value of fruits field) on the specified index using $arrayElemAt operator.

db.arrayExample.aggregate([
{ $match: { name: "Bruno" } },
{
$project: {
firstItem: { arrayElemAt:["arrayElemAt: ["arrayElemAt:["fruits", 0] },
lastItem: { arrayElemAt:["arrayElemAt: ["arrayElemAt:["fruits", -1] }
}
}
])

**Output:

array

Example 2: Using $arrayElemAt Operator in the Embedded Document

Find the elements from the outdoorGames array, which is inside the embedded document favGame, for a document with name: "Pika" using $arrayElemAt operator.

db.arrayExample.aggregate([
{ $match: { name: "Pika" } },
{
$project: {
firstItem: { arrayElemAt:["arrayElemAt: ["arrayElemAt:["favGame.outdoorGames", 0] },
item: { arrayElemAt:["arrayElemAt: ["arrayElemAt:["favGame.outdoorGames", 2] }
}
}
])

**Output:

array2

Best Practices for Using MongoDB $arrayElemAt

When working with the $arrayElemAt operator, it's important to follow best practices to ensure efficiency and correctness:

Use Cases for MongoDB $arrayElemAt

Here are some use cases discussed: