- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $slice
$slice¶
-
$slice
¶ The
$slice
modifier limits the number of array elements during a$push
operation. To project, or return, a specified number of array elements from a read operation, see the$slice
projection operator instead.To use the
$slice
modifier, it must appear with the$each
modifier. You can pass an empty array[]
to the$each
modifier such that only the$slice
modifier has an effect.The
<num>
can be:Value Description Zero To update the array <field>
to an empty array.Negative To update the array <field>
to contain only the last<num>
elements.Positive To update the array <field>
contain only the first<num>
elements.
Behavior¶
The order in which the modifiers appear is immaterial. Previous
versions required the $each
modifier to appear as the first
modifier if used in conjunction with $slice
. For a list of
modifiers available for $push
, see Modifiers.
Trying to use the $slice
modifier without the $each
modifier results in an error.
Examples¶
Slice from the End of the Array¶
A collection students
contains the following document:
The following operation adds new elements to the scores
array, and
then uses the $slice
modifier to trim the array to the
last five elements:
The result of the operation is slice the elements of the updated
scores
array to the last five elements:
Slice from the Front of the Array¶
A collection students
contains the following document:
The following operation adds new elements to the scores
array, and
then uses the $slice
modifier to trim the array to the
first three elements.
The result of the operation is to slice the elements of the updated
scores
array to the first three elements:
Update Array Using Slice Only¶
A collection students
contains the following document:
To update the scores
field with just the effects of the
$slice
modifier, specify the number of elements to slice
(e.g. -3
) for the $slice
modifier and an empty
array []
for the $each
modifier, as in the following:
The result of the operation is to slice the elements of the scores
array to the last three elements:
Use $slice
with Other $push
Modifiers¶
A collection students
has the following document:
The following $push
operation uses:
- the
$each
modifier to add multiple documents to thequizzes
array, - the
$sort
modifier to sort all the elements of the modifiedquizzes
array by thescore
field in descending order, and - the
$slice
modifier to keep only the first three sorted elements of thequizzes
array.
The result of the operation is keep only the three highest scoring quizzes:
The order of the modifiers is immaterial to the order in which the modifiers are processed. See Modifiers for details.