- Reference >
- Operators >
- Query and Projection Operators >
- Projection Operators >
- $slice (projection)
$slice (projection)¶
-
$slice¶ The
$sliceoperator controls the number of items of an array that a query returns. For information on limiting the size of an array during an update with$push, see the$slicemodifier instead.Consider the following prototype query:
This operation selects the document
collectionidentified by a field namedfieldthat holdsvalueand returns the number of elements specified by the value ofcountfrom the array stored in thearrayfield. Ifcounthas a value greater than the number of elements inarraythe query returns all elements of the array.$sliceaccepts arguments in a number of formats, including negative values and arrays. Consider the following examples:Here,
$sliceselects the first five items in an array in thecommentsfield.This operation returns the last five items in array.
The following examples specify an array as an argument to
$slice. Arrays take the form of[ skip , limit ], where the first value indicates the number of items in the array to skip and the second value indicates the number of items to return.Here, the query will only return 10 items, after skipping the first 20 items of that array.
This operation returns 10 items as well, beginning with the item that is 20th from the last item of the array.