$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.
| Category | Projection |
|---|---|
| MongoDB Version | 2.4+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <array field>: { $slice: <count> } } or { <array field>: { $slice: [ <skip>, <count> ] } }
⚙️ Parameters
| array field | The array field to slice. |
|---|---|
| count or array | A 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
- Affects only the projection, never the source document
- One argument takes the first N; two arguments are [skip, count]
- Same name as the update modifier $slice, different role
🏷️ Related Tags
💡 Related Cases
📚 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.