0
0
MongodbHow-ToBeginner · 3 min read

How to Use $pop Operator in MongoDB for Array Modification

In MongoDB, use the $pop operator to remove an element from the start or end of an array field. Specify { $pop: { arrayField: 1 } } to remove the last element or { $pop: { arrayField: -1 } } to remove the first element.
📐

Syntax

The $pop operator is used inside an update command to remove an element from an array. It takes an object where the key is the array field name and the value is either 1 or -1.

  • 1: Removes the last element of the array.
  • -1: Removes the first element of the array.
mongodb
db.collection.updateOne(
  { <filter> },
  { $pop: { <arrayField>: 1 } }
)

// or

 db.collection.updateOne(
  { <filter> },
  { $pop: { <arrayField>: -1 } }
)
💻

Example

This example shows how to remove the last and first elements from an array field called items in a document.

mongodb
db.products.insertOne({ _id: 1, items: ["apple", "banana", "cherry"] })

// Remove last element "cherry"
db.products.updateOne(
  { _id: 1 },
  { $pop: { items: 1 } }
)

// Document now: { _id: 1, items: ["apple", "banana"] }

// Remove first element "apple"
db.products.updateOne(
  { _id: 1 },
  { $pop: { items: -1 } }
)

// Document now: { _id: 1, items: ["banana"] }
Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } { "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
⚠️

Common Pitfalls

Common mistakes when using $pop include:

  • Using values other than 1 or -1 which will cause an error.
  • Trying to use $pop on fields that are not arrays.
  • Expecting $pop to remove multiple elements at once; it only removes one element per update.
mongodb
/* Wrong usage: value other than 1 or -1 */
db.products.updateOne(
  { _id: 1 },
  { $pop: { items: 2 } } // This will cause an error
)

/* Correct usage */
db.products.updateOne(
  { _id: 1 },
  { $pop: { items: -1 } }
)
📊

Quick Reference

UsageValueEffect
Remove last element1Removes the last element from the array
Remove first element-1Removes 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.
$pop only removes one element per update operation.
Ensure the target field is an array before using $pop.
Using values other than 1 or -1 with $pop causes errors.