$pop (Remove First or Last)

Last updated: 2026-10-09

$pop (Remove First or Last)

$pop removes the first (-1) or last (1) element of an array. `{ $pop: { queue: -1 } }` removes from the front; `{ $pop: { queue: 1 } }` from the end. Empty arrays are unaffected. It removes by position only — to remove by value use $pull. Useful for queues, stacks, and recent-message lists.

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

📝 Syntax

{ $pop: { <array field>: <-1 or 1> } }

⚙️ Parameters

array fieldThe array field to pop from.
direction-1 removes the first element, 1 removes the last.

Returns:The update result

▶ Example

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

// $pop: remove the queue front
// -1 front, 1 back
db.tasks.updateOne(
  { _id: 1 },
  { $pop: { queue: -1 } }
)

// Remove the back (stack pop)
db.tasks.updateOne(
  { _id: 1 },
  { $pop: { queue: 1 } }
)

Output:

// queue loses one element, from the front or the back

📌 Notes

📚 Related Tutorials

❓ FAQ

QCan $pop remove a specific value?
ANo, it removes by position only; use $pull to remove by value.
QCan $pop take only -1 or 1?
AYes, other values are invalid.
QDoes $pop error on an empty array?
ANo, it is a no-op on empty arrays.
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%

🙏 帮我们做得更好

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

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