- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $slice (aggregation)
$slice (aggregation)¶
On this page
Definition¶
-
$slice¶ Returns a subset of an array.
$slicehas one of two syntax forms:The following syntax returns elements from either the start or end of the array:
The following syntax returns elements from the specified position in the array:
Operand Description <array>Any valid expression as long as it resolves to an array. <position>Optional. Any valid expression as long as it resolves to an integer.
- If positive,
$slicedetermines the starting position from the start of the array. If<position>is greater than the number of elements, the$slicereturns an empty array. - If negative,
$slicedetermines the starting position from the end of the array. If the absolute value of the<position>is greater than the number of elements, the starting position is the start of the array.
<n>Any valid expression as long as it resolves to an integer. If
<position>is specified,<n>must resolve to a positive integer.For more information on expressions, see Expressions.
- If positive,
Behavior¶
| Example | Results |
|---|---|
Example¶
A collection named users contains the following documents:
The following example returns at most the first three elements in the
favorites array for each user:
The operation returns the following results: