MongoDB $arrayElemAt Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Array Access

What You’ll Learn

The $arrayElemAt operator returns the element at a specific index in an array. It is one of the most useful array operators in MongoDB aggregation pipelines — perfect for grabbing the first item, the last item, or any position by number.

01

Index Access

Pick one array element.

02

Zero-Based

Index 0 is first item.

03

Negative Index

-1 gets last element.

04

Field Arrays

Works on document fields.

05

Use Cases

Tags, items, history.

06

Out of Bounds

Invalid index → null.

Definition and Usage

In MongoDB’s aggregation framework, the $arrayElemAt operator returns a single element from an array at the given index. For example, { $arrayElemAt: [ "$tags", 0 ] } returns the first tag, and { $arrayElemAt: [ "$tags", -1 ] } returns the last tag. This is similar to JavaScript’s array[index] access inside a pipeline.

💡
Beginner Tip

Indexes start at 0. Use -1 for the last element instead of calculating the array length manually.

📝 Syntax

The $arrayElemAt operator takes an array and an index:

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

Syntax Rules

  • $arrayElemAt — returns the element at the specified zero-based index.
  • Negative indexes-1 is the last element, -2 is second-to-last.
  • The first argument must resolve to an array (field path, literal, or expression).
  • Use inside stages like $project, $addFields, or $set.
  • Out-of-range indexes and empty arrays return null.

💡 Index Quick Guide

For array ["a", "b", "c", "d"]:

Index 0"a" (first)
Index 2"c" (third)
Index -1"d" (last)
Index 99null (out of range)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression operator (array)
Syntax{ $arrayElemAt: [ array, index ] }
Index baseZero-based (0 = first element)
Negative indexSupported (-1 = last)
Out of boundsReturns null
First
{
  $arrayElemAt: ["$arr", 0]
}

First element

Last
{
  $arrayElemAt: ["$arr", -1]
}

Last element

Literal
{
  $arrayElemAt: [["a","b"], 1]
}

Returns "b"

Invalid
{
  $arrayElemAt: ["$arr", 99]
}

Returns null

Examples Gallery

Extract first and last tags, access order line items, and handle edge cases with index bounds.

📚 Array Indexing Basics

Pull specific elements from array fields using $project.

Sample Input Documents

Suppose you have an orders collection with a tags array:

mongosh
[
  { "_id": 1, "orderId": "ORD-101", "tags": [ "urgent", "paid", "shipped" ] },
  { "_id": 2, "orderId": "ORD-102", "tags": [ "draft", "pending" ] },
  { "_id": 3, "orderId": "ORD-103", "tags": [] }
]

Example 1 — Get the First Element (Index 0)

Extract the first tag from each order:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      tags: 1,
      firstTag: { $arrayElemAt: [ "$tags", 0 ] }
    }
  }
])

How It Works

  • ORD-101: index 0 is "urgent".
  • ORD-102: index 0 is "draft".
  • ORD-103: empty array → returns null.

📈 Practical Patterns

Use negative indexes, access nested item arrays, and guard against missing data.

Example 2 — Get the Last Element with -1

Negative indexes count from the end of the array:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      firstTag:  { $arrayElemAt: [ "$tags", 0 ] },
      lastTag:   { $arrayElemAt: [ "$tags", -1 ] },
      secondTag: { $arrayElemAt: [ "$tags", 1 ] }
    }
  }
])

How It Works

-1 always targets the last element without needing $size. Index 1 returns null when the array is too short.

Example 3 — Access an Item Inside an Object Array

Extract the product name from the first line item:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      primaryItem: {
        $arrayElemAt: [ "$items", 0 ]
      }
    }
  },
  {
    $project: {
      orderId: 1,
      primaryProduct: "$primaryItem.name",
      primaryQty: "$primaryItem.qty"
    }
  }
])

How It Works

$arrayElemAt returns the whole object at index 0. A second $project stage pulls fields from that object.

Example 4 — Safe Access with $ifNull

Provide a fallback when the index is out of range or the array is empty:

mongosh
db.orders.aggregate([
  {
    $project: {
      orderId: 1,
      statusTag: {
        $ifNull: [
          { $arrayElemAt: [ "$tags", -1 ] },
          "unknown"
        ]
      }
    }
  }
])

How It Works

When $arrayElemAt returns null (empty array or bad index), $ifNull substitutes "unknown" so reports stay readable.

🚀 Use Cases

  • First / last item — get the primary tag, latest status, or most recent history entry.
  • Line items — extract the first product from an order’s items array.
  • Time series snippets — pull a specific reading from a sensor values array.
  • Data cleanup — flatten one array element into a top-level field for reporting.

🧠 How $arrayElemAt Works

1

MongoDB resolves the array

The pipeline evaluates the array expression — a field like "$tags" or a literal array.

Input
2

Index is applied

MongoDB locates the element at the given index. Negative values count backward from the end.

Lookup
3

Element or null is returned

If the index exists, that value is returned. Otherwise MongoDB returns null.

Output
=

Single value extracted

Use the result in further stages, sorting, grouping, or display fields.

Conclusion

The $arrayElemAt operator is a straightforward way to read one position from an array inside MongoDB aggregation pipelines. It supports zero-based and negative indexes, works on field arrays and literals, and returns null when the index is invalid.

For beginners, remember: index 0 is the first item, -1 is the last, and wrap with $ifNull when you need a fallback value.

💡 Best Practices

✅ Do

  • Use -1 to get the last element without calculating length
  • Combine with $ifNull for missing or empty arrays
  • Use a second $project to read fields from object elements
  • Test with empty arrays and short arrays during development
  • Prefer $arrayElemAt when the index is dynamic or computed

❌ Don’t

  • Assume index 0 always exists on every document
  • Forget that indexes are zero-based (not one-based)
  • Use $arrayElemAt when you need the whole array
  • Confuse it with $first / $last accumulators in $group
  • Ignore null results in downstream calculations

Key Takeaways

Knowledge Unlocked

Five things to remember about $arrayElemAt

Use these points when reading array data in aggregation pipelines.

5
Core concepts
📝 02

Array Syntax

[ array, index ]

Syntax
🔢 03

Zero-Based

0 = first element.

Indexing
🔃 04

Negative Index

-1 = last element.

Shortcut
05

Out of Bounds

Returns null.

Edge case

❓ Frequently Asked Questions

$arrayElemAt returns the element at a specific index in an array. It is an aggregation expression operator used inside stages like $project and $addFields.
The syntax is { $arrayElemAt: [ <array expression>, <index> ] }. The index is zero-based, and negative values count from the end of the array.
Yes. Index -1 returns the last element, -2 returns the second-to-last, and so on.
$arrayElemAt returns null when the index is outside the array range or when the array is empty.
Dot notation like items.0 works in some query contexts. $arrayElemAt works in aggregation expressions and supports dynamic indexes and negative indexing.

Continue the Operator Series

Move on to $arrayToObject to convert arrays into key-value objects.

Next: $arrayToObject →

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.

5 people found this page helpful