Skip to content

$slice

The $slice operator returns a subset of an array. You can specify the number of elements to return, and optionally, the starting position.


📌 Syntax

{ "$slice": [ <arrayExpression>, <n> ] }

or

{ "$slice": [ <arrayExpression>, <start>, <n> ] }
  • arrayExpression: The array to slice.
  • n: The number of elements to return.
  • start: (optional) The index to start slicing from.

✅ Base Example 1 – First 2 Elements

📥 Input Document

{ "values": [10, 20, 30, 40] }

📌 Expression

{ "$slice": ["$values", 2] }

📤 Output

[10, 20]

✅ Base Example 2 – Middle Slice

📥 Input Document

{ "values": [10, 20, 30, 40, 50] }

📌 Expression

{ "$slice": ["$values", 1, 3] }

📤 Output

[20, 30, 40]

🧱 Ecommerce Example – Get First 2 Features

📌 Pipeline

[
  { "$unwind": "$items" },
  {
    "$project": {
      "product": "$items.name",
      "topFeatures": {
        "$slice": ["$items.features", 2]
      }
    }
  }
]

📥 Input Document

{
  "items": [
    {
      "name": "Smartwatch",
      "features": ["Bluetooth", "Heart Rate", "GPS", "Waterproof"]
    }
  ]
}

📤 Output

[
  {
    "product": "Smartwatch",
    "topFeatures": ["Bluetooth", "Heart Rate"]
  }
]

🔧 Common Use Cases

  • Truncate arrays
  • Return previews
  • Extract top-N items

  • $arrayElemAt, $filter, $reduce, $map, $indexOfArray

🧠 Notes

  • Negative n removes elements from the end.
  • Use with $sort to return top records before slicing.