$arrayElemAt (Get Array Element by Index)
Last updated: 2026-10-09
$arrayElemAt (Get Array Element by Index)
$arrayElemAt returns the element at a given index position in an array. It is the core operator for position-based array access in aggregation expressions, often used to grab the first item of an order, the last element of an array, or a specific position inside $project. Indexes start at 0, negative indexes count from the end, and out-of-range access returns null instead of throwing. Unlike $first/$last, $arrayElemAt can reach any position, making it more flexible.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $arrayElemAt: [ <array>, <index> ] }
⚙️ Parameters
| array | The array, or an expression resolving to an array. |
|---|---|
| index | An integer index; negative values count from the end, -1 is the last element. |
Returns:The element at the given index; null if out of range or the array is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $arrayElemAt: get the first item of an order
db.orders.aggregate([
{ $project: {
firstItem: { $arrayElemAt: ['$items', 0] }
} }
])
Output:
{ '_id': 1, 'firstItem': { 'sku': 'A01', 'qty': 2 } }
{ '_id': 2, 'firstItem': { 'sku': 'B02', 'qty': 1 } }
📌 Notes
- Indexes start at 0; use -1 for the last element without computing $size first
- Out-of-range access returns null, not an error; pair with $ifNull for a fallback
- Unlike $first/$last which only reach the ends, $arrayElemAt accesses any position
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QHow do I get the last element of an array with $arrayElemAt?
AUse -1 as the index, e.g. { $arrayElemAt: ['$arr', -1] }, without computing the length first.
QDoes an out-of-range index throw an error?
ANo — it returns null. Wrap with $ifNull to supply a default.
QWhat is the difference between $arrayElemAt and $first?
A$first always takes the first element; $arrayElemAt takes any index, including negatives, so it is more flexible.