MongoDB $slice Operator

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 4 Examples
Array Operations

What You’ll Learn

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.

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.

📝 Syntax

$slice supports aggregation expressions, find projections, and update modifiers:

Aggregation Expression

mongosh
{ $slice: [ <array>, <n> ] }
{ $slice: [ <array>, <position>, <n> ] }

Find Projection

mongosh
{ <arrayField>: { $slice: <n> } }
{ <arrayField>: { $slice: [ <position>, <n> ] } }

Syntax Rules

  • Two-arg form[ array, n ]: positive n takes from the start; negative n takes from the end.
  • Three-arg form[ array, position, n ]: start at 0-based position, return n elements.
  • If the array is shorter than requested, MongoDB returns as many elements as available.
  • Aggregation: use in $project, $addFields, or $set.
  • Non-array input in aggregation causes an error.

💡 $slice Forms on [1, 2, 3, 4, 5]

$slice [ arr, 2 ][1, 2] (first two)
$slice [ arr, -2 ][4, 5] (last two)
$slice [ arr, 1, 3 ][2, 3, 4] (start at index 1, take 3)
$slice [ arr, 2, 10 ][3, 4, 5] (only 3 left)

⚡ Quick Reference

QuestionAnswer
Operator typeAggregation expression, projection, and update modifier
Aggregation syntax{ $slice: [ arr, n ] } or [ arr, pos, n ]
Positive nElements from the start (two-arg) or count from position (three-arg)
Negative n (two-arg)Last |n| elements
Common stages$project, $addFields, find projection
First 3
{
  $slice: ["$tags", 3]
}

Start of array

Last 2
{
  $slice: ["$logs", -2]
}

End of array

Window
{
  $slice: ["$items", 2, 4]
}

Index 2, take 4

Find proj.
{
  comments: { $slice: 5 }
}

First 5 in query

Examples Gallery

Take the first few tags, grab the latest comments, paginate with a position window, and limit arrays in find projections with $slice.

📚 First N Elements

Preview the first three tags from each article using $project.

Sample Input Documents

Suppose you have an articles collection:

mongosh
[
  {
    "_id": 1,
    "title": "MongoDB Tips",
    "tags": ["mongodb", "database", "nosql", "aggregation", "tutorial"]
  },
  {
    "_id": 2,
    "title": "Node.js Guide",
    "tags": ["nodejs", "javascript"]
  },
  {
    "_id": 3,
    "title": "Draft",
    "tags": []
  }
]

Example 1 — First Three Tags

Return only the first three tags per document:

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      topTags: { $slice: [ "$tags", 3 ] }
    }
  }
])

How It Works

The two-argument form with positive 3 takes elements from index 0 through 2. Shorter arrays return all available elements.

📈 End, Window, and Projection

Recent comments, paginated windows, and find-query previews.

Example 2 — Last Two Comments

Use a negative n to take elements from the end:

mongosh
db.posts.aggregate([
  {
    $project: {
      title: 1,
      recentComments: {
        $slice: [ "$comments", -2 ]
      }
    }
  }
])

// comments: ["a", "b", "c", "d", "e"]
// recentComments: ["d", "e"]

How It Works

Negative n counts from the end of the array. This pattern is common for “latest activity” previews.

Example 3 — Paginate With Position and Count

Skip the first two items and take the next three (page-style window):

mongosh
db.articles.aggregate([
  {
    $project: {
      title: 1,
      tagPage: {
        $slice: [ "$tags", 2, 3 ]
      }
    }
  }
])

// tags: ["mongodb", "database", "nosql", "aggregation", "tutorial"]
// tagPage: ["nosql", "aggregation", "tutorial"]

How It Works

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.

🚀 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.

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.

💡 Best Practices

✅ Do

  • Use negative n for “latest N” previews
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about $slice

Use these points when extracting array subsets in MongoDB.

5
Core concepts
📝 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.

Continue the Operator Series

Move on to $sortArray to sort array elements before slicing, or review $size for counting.

Next: $sortArray →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

5 people found this page helpful