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

CategoryArray
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $slice: [ <array>, <count> ] } or { $slice: [ <array>, <skip>, <count> ] }

⚙️ Parameters

arrayThe array to slice.
countThe number of elements to take; when negative in the two-argument form, takes the last n from the end.
skipOptional; 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

📚 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏