How to Use $arrayElemAt in Aggregation in MongoDB
In MongoDB aggregation, use
$arrayElemAt to get the element at a specific index from an array. It takes two arguments: the array and the zero-based index. For example, { $arrayElemAt: ["$arrayField", 1] } returns the second element of arrayField.Syntax
The $arrayElemAt operator takes two arguments inside an array:
- array: The array field or expression you want to access.
- index: The zero-based position of the element you want to retrieve.
It returns the element at the specified index or null if the index is out of bounds.
json
{ $arrayElemAt: [ <array>, <index> ] }Example
This example shows how to use $arrayElemAt in an aggregation pipeline to get the second element from an array field called scores in each document.
mongodb
db.students.aggregate([
{
$project: {
name: 1,
secondScore: { $arrayElemAt: ["$scores", 1] }
}
}
])Output
[
{ "_id": ObjectId("..."), "name": "Alice", "secondScore": 85 },
{ "_id": ObjectId("..."), "name": "Bob", "secondScore": 90 },
{ "_id": ObjectId("..."), "name": "Charlie", "secondScore": null }
]
Common Pitfalls
- Using a negative index without understanding it returns elements from the end (e.g., -1 returns the last element).
- Index out of bounds returns
null, which might cause unexpected results if not handled. - Passing a non-array value as the first argument causes errors.
Always ensure the field is an array and the index is within range.
mongodb
/* Wrong: index out of bounds returns null */ db.collection.aggregate([ { $project: { elem: { $arrayElemAt: ["$arrayField", 10] } } } ]) /* Right: check array length before accessing or handle null */
Quick Reference
| Usage | Description |
|---|---|
| { $arrayElemAt: [ | Returns element at zero-based |
| Negative index | Counts from the end (-1 is last element) |
| Index out of range | Returns null |
| Non-array input | Causes error |
Key Takeaways
Use $arrayElemAt to get an element at a specific zero-based index from an array in aggregation.
Negative indexes count from the end of the array (-1 is last element).
If the index is out of bounds, $arrayElemAt returns null.
Ensure the first argument is an array to avoid errors.
Use $arrayElemAt inside $project or other pipeline stages to extract array elements.