$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.
| Category | Update Array |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $pop: { <array field>: <-1 or 1> } }
⚙️ Parameters
| array field | The 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
- Accepts only -1 or 1 as the direction
- To remove by value use $pull, not $pop
- No-op on empty arrays
🏷️ Related Tags
💡 Related Cases
Array and Nested Document Queries
Document Update: A Detailed Explanation of `updateOne` and `updateMany`
📚 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.