- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $slice
$slice¶
-
$slice¶ The
$slicemodifier limits the number of array elements during a$pushoperation. To project, or return, a specified number of array elements from a read operation, see the$sliceprojection operator instead.To use the
$slicemodifier, it must appear with the$eachmodifier. You can pass an empty array[]to the$eachmodifier such that only the$slicemodifier 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
$eachmodifier to add multiple documents to thequizzesarray, - the
$sortmodifier to sort all the elements of the modifiedquizzesarray by thescorefield in descending order, and - the
$slicemodifier to keep only the first three sorted elements of thequizzesarray.
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.