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

CategoryUpdate Modifier
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $push: { <array field>: { $each: [ <value> ], $slice: <count> } } }

⚙️ Parameters

array fieldThe array field to cap.
countThe 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

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

🙏 帮我们做得更好

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

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