The $slice operator returns a portion of an array — the first N elements, the last N elements, or a window starting at a specific position. Use it in aggregation pipelines, find projections, and capped-array updates.
01
Array Subset
Take part of array.
02
Two Forms
2 or 3 arguments.
03
Negative n
From the end.
04
Projection
Limit in find().
05
Use Cases
Preview, paginate.
06
Capped arrays
$push + $slice.
Fundamentals
Definition and Usage
MongoDB’s $slice operator extracts elements from an array without modifying the original document (in read contexts). In aggregation, { $slice: [ "$comments", 3 ] } returns the first three comments. With a negative number, { $slice: [ "$comments", -2 ] } returns the last two.
This is ideal when you need a preview of a long list — recent activity, top tags, or paginated results — without transferring the entire array over the network.
💡
Beginner Tip
Pair $slice with $size when you need both a count and a preview: use $size for the total length and $slice for the first few items.
Foundation
📝 Syntax
$slice supports aggregation expressions, find projections, and update modifiers:
The three-argument form uses a 0-based position and a count n. Position 2 starts at the third element.
Example 4 — Limit Array in a Find Projection
Return only the first five comments without an aggregation pipeline:
mongosh
db.posts.find(
{ _id: 1 },
{ comments: { $slice: 5 } }
)
// Returns first 5 comments only in the result
How It Works
Find projection $slice limits what the client receives. The full array remains stored in the document unless you update it separately.
Bonus — Capped Array on Update
Keep only the last 10 comments when pushing a new one:
mongosh
db.posts.updateOne(
{ _id: 1 },
{
$push: {
comments: {
$each: [ { text: "New comment", at: new Date() } ],
$slice: -10
}
}
}
)
// Appends the comment, then keeps only the last 10
How It Works
Combine $push, $each, and $slice to maintain a fixed-size rolling list without manual trimming.
Applications
🚀 Use Cases
UI previews — show the first few tags, skills, or categories without loading full lists.
Recent activity — display the last N log entries or comments with negative $slice.
Pagination — use the three-arg form for skip-and-take windows over arrays.
Capped collections in documents — trim arrays on insert with $push + $slice.
🧠 How $slice Works
1
MongoDB reads the source array
The input resolves to an array field, literal, or nested expression.
Input
2
Start index and count are applied
Two-arg form uses start/end logic with sign of n. Three-arg form uses explicit position and length.
Slice
3
A new subset array is returned
If fewer elements exist than requested, MongoDB returns whatever is available without error.
Output
=
✂
Subset array
Use in projections, API responses, or chained with $size for totals.
Wrap Up
Conclusion
The $slice operator extracts portions of arrays for previews, pagination, and capped updates. Learn both the two-argument form (first or last N) and the three-argument form (position + count).
Use aggregation $slice when building computed fields; use find projection $slice when you only need to limit returned data. Next in the series: $sortArray.
Use the three-arg form for pagination-style windows
Combine with $size to show “3 of 12” in UIs
Use $push + $slice to cap growing arrays on update
Guard missing arrays with $ifNull: [ "$field", [] ] before slicing
❌ Don’t
Confuse aggregation $slice with JavaScript Array.slice() argument order in three-arg form
Assume find projection $slice modifies stored data — it only limits output
Forget that position is 0-based in the three-arg form
Pass non-array values without validation in aggregation
Use $slice when you need sorted results first — sort with $sortArray before slicing
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $slice
Use these points when extracting array subsets in MongoDB.
5
Core concepts
✂01
Subset
Part of array.
Purpose
📝02
[ arr, n ]
First or last.
Syntax
🛠03
Negative n
From the end.
Rule
🗃04
[ arr, pos, n ]
Window slice.
Pagination
⚠05
3 contexts
Agg / find / update.
Important
❓ Frequently Asked Questions
$slice returns a subset of elements from an array. In aggregation it is { $slice: [ array, n ] } or { $slice: [ array, position, n ] }. In find projections it limits how many array elements are returned: { field: { $slice: 5 } }.
Two forms: { $slice: [ <array>, <n> ] } returns the first n elements (or last |n| if n is negative). { $slice: [ <array>, <position>, <n> ] } starts at position (0-based) and returns n elements.
A positive n takes elements from the start of the array. A negative n takes elements from the end. For example, $slice on [1,2,3,4,5] with n=2 returns [1,2]; with n=-2 returns [4,5].
Aggregation $slice is an expression operator inside $project or $addFields that builds a new array field. Find projection $slice limits array elements in query results without running an aggregation pipeline.
Yes. With $push, $each, and $slice together you can append items and keep only the most recent N. Example: { $push: { comments: { $each: [newComment], $slice: -10 } } } keeps the last 10 comments.