MongoDB $arrayElemAt Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $arrayElemAt?

$arrayElemAt is a MongoDB aggregation expression that returns one element from an array at a given index. Indexes are zero-based; negative indexes count from the end (-1 = last).

Remember
$arrayElemAt = array[index] for aggregation

{ $arrayElemAt: [ <array>, <index> ] }

0, 1, 2, …  → from the start
-1, -2, …   → from the end

out of range → no result (missing / null)
missing array → null
UsePrefer
One element by index$arrayElemAt
A subarray / slice$slice
Array length$size

How to Use $arrayElemAt in MongoDB

Pass the array and the index, then store or project the returned value.

  1. Choose an expression stage ($addFields or $project).
  2. Pass [ "$field", index ] to $arrayElemAt.
  3. Use 0 for first, -1 for last, or any other integer index.
  4. Handle missing / out-of-range results if your data can be short or empty.
PieceRequired?Role
$arrayElemAtYesPick one element by index
ArrayYesField path or expression that resolves to an array
IndexYesInteger (0-based; negatives from the end)

Pseudocode

Pseudocode
for each document:
    arr = evaluate(arrayExpression)
    idx = evaluate(indexExpression)
    if arr is missing / undefined:
        result = null
    else if idx is out of range for arr:
        result = missing   // no value
    else if idx >= 0:
        result = arr[idx]           // from start
    else:
        result = arr[length + idx]  // from end (-1 = last)
    emit { ..., field: result }

Cheat Sheet

Keep these facts handy while picking array elements.

TopicDetail
TypeAggregation expression (not a find filter alone)
Syntax{ $arrayElemAt: [ <array>, <index> ] }
First element{ $arrayElemAt: [ "$arr", 0 ] }
Last element{ $arrayElemAt: [ "$arr", -1 ] }
Sample[1, 2, 3] + index -2 → 2
Out of rangeNo result (missing / null)
vs $sliceOne value vs a subarray

Live Preview

Array: ["chocolate", "apples", "pie"]. Change the index and watch $arrayElemAt return one value.

Simulates $arrayElemAt with zero-based and negative indexes (same idea as the mongosh examples).

Result
favorites = ["chocolate", "apples", "pie"]
index = 0
$arrayElemAt → "chocolate"

{ value: "chocolate" }

Worked Walkthrough — First and Last Favorite

Array ["chocolate", "apples", "pie"]. Index 0 is first; index -1 is last.

Calculation
favorites = ["chocolate", "apples", "pie"]
indexes:       0             1         2
from end:     -3            -2        -1

$arrayElemAt(favorites, 0)  → "chocolate"  (first)
$arrayElemAt(favorites, 1)  → "apples"
$arrayElemAt(favorites, -1) → "pie"        (last)
$arrayElemAt(favorites, -2) → "apples"
$arrayElemAt(favorites, 5)  → (no result)

Tip: -1 always means “the last item” without knowing the length.

MongoDB Examples

We use a small users collection with a favorites array. First we pick the first and last items, then we pick the second item. Insert the sample data once in mongosh.

Example 1 — Sample Data

Imagine three users. Each has a name and a favorites list. We save them in a collection named users.

mongosh
db.users.insertMany([
  { _id: 1, name: "dave123", favorites: ["chocolate", "cake", "apples"] },
  { _id: 2, name: "li", favorites: ["apples", "pie"] },
  { _id: 3, name: "ahn", favorites: ["pears", "pie", "cherries"] }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps three documents in users. Run find() to see them:

mongosh
db.users.find()

Read those documents like this:

Field in MongoDBExamplePlain English
_id1User id for this lesson
name"dave123"User name
favorites["chocolate", "cake", "apples"]Ordered list of favorite items
Picture
dave123 favorites:

  index:   0            1         2
         ["chocolate", "cake", "apples"]
  end:    -3           -2        -1

  first (0)  → "chocolate"
  last (-1)  → "apples"
  second (1) → "cake"

How It Works

  1. Insert once. insertMany adds three user documents.
  2. MongoDB stores arrays as written. Order in favorites matters for indexes.
  3. find() shows the same shape. What you inserted is what you get back—ready for $arrayElemAt next.

Example 2 — First and Last Elements

Goal: add first and last using indexes 0 and -1.

mongosh
db.users.aggregate([
  {
    $addFields: {
      first: { $arrayElemAt: [ "$favorites", 0 ] },
      last: { $arrayElemAt: [ "$favorites", -1 ] }
    }
  }
]);

How It Works

  1. Read the stored array. "$favorites" is the list for each user.
  2. Index 0. $arrayElemAt(..., 0) returns the first favorite.
  3. Index -1. $arrayElemAt(..., -1) returns the last favorite—even when list lengths differ.
  4. Keep all fields. $addFields adds first and last next to the original document.

Example 3 — Second Element

Same users, but pick index 1 (the second item). Users with fewer than two favorites get no value for that field.

mongosh
db.users.aggregate([
  {
    $addFields: {
      second: { $arrayElemAt: [ "$favorites", 1 ] }
    }
  }
]);

How It Works

  1. Same stored documents. Still using the three users from Example 1.
  2. Index 1 means second slot. dave123 → cake; li → pie; ahn → pie.
  3. Zero-based reminder. First is 0, second is 1—not 2.
  4. Short arrays. If a list had only one item, index 1 would be out of range and return no result.

Edge Cases & Pitfalls

Check these before using $arrayElemAt in production pipelines.

bounds

Out-of-range indexes

An index past the array ends returns no result. Guard with $size or $cond when a value is required.

missing

Missing array → null

If the array field is missing or undefined, $arrayElemAt returns null.

zero

Indexes start at 0

The first element is index 0, not 1. Off-by-one mistakes are common.

slice

Need several items? Use $slice

$arrayElemAt returns one value. For a range of elements, use $slice.

Performance Notes

ApproachCostBest for
$arrayElemAtO(1) element accessFirst / last / fixed position
vs $sliceBuilds a subarrayMultiple consecutive elements
vs $unwindExplodes documentsPer-element processing (heavier)

Prefer $arrayElemAt when you only need one position. Filter early with $match so later stages process fewer documents.

Key Takeaways

  • Role: return one array element by index.
  • Indexes: 0 = first, -1 = last.
  • Bounds: out of range → no result; missing array → null.
  • Need a range? use $slice instead.

One line: $arrayElemAt answers “what is at this index?”—with 0 from the start and -1 from the end.

Frequently Asked Questions

$arrayElemAt returns the element at a given index in an array. Use it inside aggregation expression stages such as $project and $addFields.
Use { $arrayElemAt: [ <array>, <index> ] }. The index must resolve to an integer. Indexes are zero-based.
Yes. -1 is the last element, -2 is the second-to-last, and so on.
If the index is outside the array bounds, $arrayElemAt does not return a result (the field is missing / null in practice). If the array expression is missing or undefined, it returns null.
Use index 0 for the first element and index -1 for the last element.
$arrayElemAt returns one element. $slice returns a subarray (a slice of elements).

Next: $arrayToObject

Turn an array of key/value pairs into a document.

$arrayToObject tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful