- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $arrayElemAt (aggregation)
$arrayElemAt (aggregation)¶
On this page
Definition¶
-
$arrayElemAt¶ Returns the element at the specified array index.
$arrayElemAthas the following syntax:The
<array>expression can be any valid expression that resolves to an array.The
<idx>expression can be any valid expression that resolves to an integer:- If the
<idx>expression resolves to zero or a positive integer,$arrayElemAtreturns the element at theidxposition, counting from the start of the array. - If the
<idx>expression resolves to a negative integer,$arrayElemAtreturns the element at theidxposition, counting from the end of the array.
If
idxexceeds the array bounds,$arrayElemAtdoes not return a result.For more information on expressions, see Expressions.
- If the
Behavior¶
For more information on expressions, see Expressions.
| Example | Results |
|---|---|
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] } |
1 |
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] } |
2 |
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] } |
Example¶
A collection named users contains the following documents:
The following example returns the first and last element in the
favorites array:
The operation returns the following results: