$slice (projection)
$slice
- The
$slice
operator controls the number of items of anarray that a query returns. For information on limiting the size ofan array during an update with$push
, see the$slice
modifier instead.
db.collection.find()
operations on views do not support $slice
projection operator.
Consider the following prototype query:
- db.collection.find( { field: value }, { array: {$slice: count } } );
This operation selects the document collection
identified by afield named field
that holds value
and returns the numberof elements specified by the value of count
from the arraystored in the array
field. If count
has a value greaterthan the number of elements in array
the query returns allelements of the array.
$slice
accepts arguments in a number of formats,including negative values and arrays. Consider the followingexamples:
- db.posts.find( {}, { comments: { $slice: 5 } } )
Here, $slice
selects the first five items in an arrayin the comments
field.
- db.posts.find( {}, { comments: { $slice: -5 } } )
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 thefirst value indicates the number of items in the array to skip andthe second value indicates the number of items to return.
- db.posts.find( {}, { comments: { $slice: [ 20, 10 ] } } )
Here, the query will only return 10 items, after skipping the first20 items of that array.
- db.posts.find( {}, { comments: { $slice: [ -20, 10 ] } } )
This operation returns 10 items as well, beginning with the itemthat is 20th from the last item of the array.