$slice (Project Array Subset)

Last updated: 2026-10-09

$slice (Project Array Subset)

$slice in a projection returns a subset of an array field without modifying the document. `{ tags: { $slice: 2 } }` returns the first 2 elements; `{ tags: { $slice: [1, 3] } }` skips 1 and takes 3. Common for list pages that show only the first few comments or attachments. It shares its name with the update modifier $slice, but serves a different purpose.

CategoryProjection
MongoDB Version2.4+
Example Languagemongosh (Shell)

📝 Syntax

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

⚙️ Parameters

array fieldThe array field to slice.
count or arrayA count for the first N, or [skip, count] to skip then take.

Returns:Documents projected with the requested array subset

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $slice: return only the first 3 tags
db.articles.find(
  { _id: 1 },
  { title: 1, tags: { $slice: 3 } }
)

// Skip 1, take 2
db.articles.find(
  { _id: 1 },
  { comments: { $slice: [1, 2] } }
)

Output:

// Returns the title and first 3 tags; the second query skips 1 comment and takes 2

📌 Notes

📚 Related Tutorials

❓ FAQ

QIs projection $slice the same as the update $slice?
ANo. Projection $slice shapes the result; update $slice caps the array after $push.
QHow do I take the last elements of an array?
AUse a negative: { tags: { $slice: -3 } } takes the last 3.
QCan $slice combine with other projections?
AYes, as long as they do not conflict.
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%

🙏 帮我们做得更好

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

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