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.
Fundamentals
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.
Foundation
📝 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 99 → null (out of range)
Cheat Sheet
⚡ Quick Reference
Question
Answer
Operator type
Aggregation expression operator (array)
Syntax
{ $arrayElemAt: [ array, index ] }
Index base
Zero-based (0 = first element)
Negative index
Supported (-1 = last)
Out of bounds
Returns 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
Hands-On
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:
When $arrayElemAt returns null (empty array or bad index), $ifNull substitutes "unknown" so reports stay readable.
Applications
🚀 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.
Wrap Up
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.
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
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $arrayElemAt
Use these points when reading array data in aggregation pipelines.
5
Core concepts
📦01
Index Access
One element by number.
Purpose
📝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.