MongoDB $slice Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $slice?

$slice returns a sub-array—the first N items, the last N items, or a window starting at a position. Use it in aggregation, find projections, and capped $push updates.

Remember
$slice = take part of an array

Aggregation:
  { $slice: [ "$favorites", 3 ] }   → first 3
  { $slice: [ "$favorites", -2 ] }  → last 2
  { $slice: [ "$favorites", 1, 2 ] } → from index 1, take 2

Find projection:
  { favorites: { $slice: 3 } }

Array shorter than n → return what exists
non-array (agg) → error
UsePrefer
Build a new array fieldAggregation $slice
Limit arrays in query resultsFind projection $slice
Keep only recent N after push$push + $each + $slice

How to Use $slice in MongoDB

Pick compute mode, projection mode, or capped-update mode.

  1. To compute a subset: use $project / $addFields with { $slice: [ "$field", n ] }.
  2. To limit arrays in results: use find({}, { field: { $slice: n } }).
  3. Positive n = from the start; negative n = from the end (two-arg form).
  4. For a mid-array window: use { $slice: [ "$field", position, n ] } (then n must be positive).
ContextFormResult
Aggregation{ $slice: [ arr, n ] }New array expression
Find projection{ field: { $slice: n } }Trimmed field in result
With position{ $slice: [ arr, pos, n ] }Window from pos

Pseudocode

Pseudocode
// Aggregation — two args
arr = evaluate(arrayExpression)
if arr is not an array: error
if n > 0:  result = arr[0 .. n-1]
if n < 0:  result = arr[end+|n| .. end]
emit { ..., field: result }

// Aggregation — three args
start = position (0-based; negative counts from end)
result = arr[start .. start+n-1]   // n must be > 0

// Find projection
return document, but only show sliced field

Cheat Sheet

Keep these facts handy while slicing arrays.

TopicDetail
Agg 2-arg{ $slice: [ <array>, <n> ] }
Agg 3-arg{ $slice: [ <array>, <pos>, <n> ] }
Projection{ field: { $slice: <n> } }
Positive nFrom the start
Negative nFrom the end (2-arg only)
Short arrayReturns available elements
Sample[1,2,3,4,5] + -2 → [4,5]

Live Preview

Watch aggregation $slice on ["chocolate","cake","butter","pie","nuts"].

Simulates aggregation $slice (same idea as the mongosh examples below).

Result
favorites = ["chocolate", "cake", "butter", "pie", "nuts"]
$slice: [ "$favorites", 3 ]

→ ["chocolate", "cake", "butter"]

Worked Walkthrough — First Three Favorites

A user has favorites: ["chocolate", "cake", "butter", "pie", "nuts"]. Show only the first three.

Calculation
Document:
  { name: "dave123", favorites: ["chocolate","cake","butter","pie","nuts"] }

$slice(favorites, 3):
  index 0 → "chocolate"
  index 1 → "cake"
  index 2 → "butter"
  stop (n = 3)

Result → ["chocolate", "cake", "butter"]

$slice(favorites, -2) → ["pie", "nuts"]
$slice(favorites, 1, 2) → ["cake", "butter"]

MongoDB Examples

We use a small users collection. First we slice in aggregation, then limit arrays with a find projection. Run these in mongosh after inserting the sample data once.

Example 1 — Sample Data

Imagine four users. Each has a favorites array of different lengths.

mongosh
db.users.insertMany([
  { _id: 1, name: "dave123", favorites: ["chocolate", "cake", "butter", "pie", "nuts"] },
  { _id: 2, name: "li", favorites: ["apples", "pudding", "pie"] },
  { _id: 3, name: "ahn", favorites: ["pears", "pecans", "chocolate", "berries"] },
  { _id: 4, name: "ty", favorites: ["ice cream"] }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps four documents. Run find() to see them:

mongosh
db.users.find()

Read one document like this:

Field in MongoDBValue (doc 1)Plain English
name"dave123"Username
favorites["chocolate", …]Array of favorite foods

How It Works

  1. Insert once. Four documents land in users.
  2. Different lengths. Long lists and a one-item list show how $slice behaves when short.
  3. find() shows the same shape. Ready for slicing next.

Example 2 — Slice in Aggregation

Goal: project each name with at most the first three favorites.

mongosh
db.users.aggregate([
  {
    $project: {
      name: 1,
      threeFavorites: { $slice: [ "$favorites", 3 ] }
    }
  }
]);

How It Works

  1. $project builds fields. Keep name; add threeFavorites.
  2. $slice takes 3. Positive n starts at index 0.
  3. Long arrays shrink. dave123 and ahn lose extras.
  4. Short arrays stay short. ty only has one item—MongoDB returns that one item, not an error.

Example 3 — Find Projection

Goal: return each user, but only the last two favorites in the result (document in the database is unchanged).

mongosh
db.users.find(
  {},
  { name: 1, favorites: { $slice: -2 } }
);

How It Works

  1. Empty filter. {} matches every document.
  2. Projection $slice. -2 keeps the last two elements in the response.
  3. Stored data unchanged. This only affects what find() returns.
  4. ty still has one. Negative slice cannot invent missing items.

Edge Cases & Pitfalls

Check these before using $slice in production pipelines.

type

Aggregation needs a real array

Missing fields or strings make aggregation $slice error. Guard with $isArray when unsure.

args

Three-arg form: n must be positive

With a position, n cannot be negative. Use two-arg form for “last N”.

pos

Position past the end → empty

If positive position is beyond the array length, aggregation returns [].

vs

Projection ≠ rewrite

Find $slice only shapes the response. To change stored arrays, use an update ($push/$pull/$set).

Performance Notes

ApproachCostBest for
Agg $slicePer-doc copy of N itemsPreviews in pipelines
Find projection $sliceSmaller network payloadAPI list responses
Capped $push + $sliceWrite-time trimRecent-activity lists

Slicing is cheap for small N. Prefer projecting a short window instead of shipping huge arrays to the client. For unbounded growth (comments, events), cap with $push + $slice on write.

Key Takeaways

  • Agg: $slice builds a sub-array.
  • +n / −n: start vs end (2-arg).
  • Projection trims results only.
  • Short arrays return what exists.

One line: $slice answers “give me part of this array”—in pipelines, projections, or capped updates.

Frequently Asked Questions

$slice returns a subset of an array. In aggregation: { $slice: [ "$favorites", 3 ] }. In find projections: { favorites: { $slice: 3 } }. With $push updates you can also cap how many elements stay after an append.
Aggregation: { $slice: [ <array>, <n> ] } or { $slice: [ <array>, <position>, <n> ] }. Projection: { field: { $slice: <n> } } or { field: { $slice: [ <position>, <n> ] } }.
With two arguments, positive n takes from the start; negative n takes from the end. Example: array [1,2,3,4,5] with n=2 → [1,2]; with n=-2 → [4,5].
Yes. Use the three-argument form: { $slice: [ "$tags", 1, 2 ] } starts at index 1 (0-based) and returns 2 elements. In that form, n must be a positive integer.
MongoDB returns as many elements as exist—no error. Asking for 5 from a 2-element array returns both elements.
Aggregation builds a new array field inside $project / $addFields. Find projection only limits how many array elements appear in the query result—it does not run a full pipeline.

Next: $sortArray

Sort array elements inside aggregation expressions.

$sortArray tutorial →

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.

9 people found this page helpful