How to Use $pop Operator in MongoDB: Syntax and Examples
The
$pop operator in MongoDB removes the first or last element from an array field in a document. Use { $pop: { field: 1 } } to remove the last element and { $pop: { field: -1 } } to remove the first element.Syntax
The $pop operator is used inside an update command to remove an element from an array.
- field: The name of the array field to modify.
- 1: Removes the last element of the array.
- -1: Removes the first element of the array.
mongodb
db.collection.updateOne(
{ <filter> },
{ $pop: { <field>: 1 } } // removes last element
)
// or
db.collection.updateOne(
{ <filter> },
{ $pop: { <field>: -1 } } // removes first element
)Example
This example shows how to remove the last and first element from an array field named scores in a document.
mongodb
db.students.insertOne({ name: "Alice", scores: [85, 90, 95] })
// Remove last element (95)
db.students.updateOne(
{ name: "Alice" },
{ $pop: { scores: 1 } }
)
// Document after update: { name: "Alice", scores: [85, 90] }
// Remove first element (85)
db.students.updateOne(
{ name: "Alice" },
{ $pop: { scores: -1 } }
)
// Document after update: { name: "Alice", scores: [90] }Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
{ "name" : "Alice", "scores" : [ 85, 90 ] }
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
{ "name" : "Alice", "scores" : [ 90 ] }
Common Pitfalls
Common mistakes when using $pop include:
- Using values other than
1or-1which are ignored. - Applying
$popon fields that are not arrays causes no change. - Expecting
$popto remove multiple elements; it only removes one element per update.
mongodb
/* Wrong: Using 2 instead of 1 or -1 */ db.students.updateOne( { name: "Alice" }, { $pop: { scores: 2 } } // Ignored, no change ) /* Correct: Use 1 or -1 */ db.students.updateOne( { name: "Alice" }, { $pop: { scores: 1 } } // Removes last element )
Quick Reference
| Usage | Value | Effect |
|---|---|---|
| Remove last element | 1 | Removes the last element from the array |
| Remove first element | -1 | Removes the first element from the array |
Key Takeaways
Use $pop with 1 to remove the last element of an array field.
Use $pop with -1 to remove the first element of an array field.
Only one element is removed per update operation with $pop.
Using values other than 1 or -1 for $pop has no effect.
Ensure the target field is an array before using $pop.