$slice (Get Array Subset)
Last updated: 2026-10-09
$slice (Get Array Subset)
$slice extracts a portion of an array. It supports two forms: the two-argument form takes the first n elements (or the last n when n is negative), and the three-argument form skips a number of elements then takes a specified count. Typical uses: paginating comments, taking the most recent orders, or capping the number of tags returned. It returns a new array without modifying the original; a null argument yields null. It is the array counterpart of $substr for strings.
| Category | Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $slice: [ <array>, <count> ] } or { $slice: [ <array>, <skip>, <count> ] }
⚙️ Parameters
| array | The array to slice. |
|---|---|
| count | The number of elements to take; when negative in the two-argument form, takes the last n from the end. |
| skip | Optional; elements to skip first in the three-argument form; negative starts counting back from the end. |
Returns:The extracted sub-array; null if an argument is null
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $slice: take the first 3 tags
db.posts.aggregate([
{ $project: {
topTags: { $slice: ['$tags', 3] }
} }
])
Output:
{ '_id': 1, 'topTags': [ 'mongo', 'db', 'nosql' ] }
📌 Notes
- Two-argument form [array, n]: positive n takes the first n, negative n takes the last n
- Three-argument form [array, skip, count]: a negative skip starts counting back from the end
- Slicing beyond the array length never throws; it returns whatever exists
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QHow do I take the last elements with $slice?
AUse a negative count, e.g. { $slice: ['$arr', -3] } for the last 3.
QDoes $slice support pagination?
AYes — { $slice: ['$arr', 10, 10] } skips 10 and takes 10.
QDoes slicing beyond the length throw?
ANo — it returns the elements that exist, without padding null.