$slice (Cap Array Length, Update)
Last updated: 2026-10-09
$slice (Cap Array Length, Update)
$slice as an update modifier caps an array's length after $push. `{ $push: { log: { $each: [msg], $slice: -10 } } }` keeps only the latest 10 entries. Negative values trim from the end, positive from the start. Combined with $each it creates a rolling log — same name as the projection $slice but a different role.
| Category | Update Modifier |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $push: { <array field>: { $each: [ <value> ], $slice: <count> } } }
⚙️ Parameters
| array field | The array field to cap. |
|---|---|
| count | The count to keep; negative keeps from the end. |
Returns:The update result
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $slice: keep the latest 10 log entries
// -10 keeps 10 from the end
db.devices.updateOne(
{ _id: 1 },
{ $push: { log: { $each: ['boot ok'], $slice: -10 } } }
)
Output:
// After appending, log is trimmed to the latest 10 entries
📌 Notes
- Must be used with $each inside $push
- Negative keeps from the end; positive from the start
- Same name as projection $slice, different role
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QIs the update $slice the same as the projection $slice?
ANo. The update $slice trims the array; projection $slice only shapes results.
QWhat does $slice: -10 mean?
AKeep 10 entries from the end, creating a rolling log.
QMust $slice be paired with $each?
AYes, since MongoDB 5.0 $slice works only with $each.