MongoDB $pop

In MongoDB, you can use the $pop operator to remove the first or last element from an array.

Use $pop in conjunction with a method such as update() to update the specified document with the change.

Use -1 to remove the first element, and 1 to remove the last.

Example

Suppose we have a collection called products with the following documents:

{ "_id" : 1, "prod" : "Bat", "sizes" : [ "S", "M", "L", "XL" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "M", "L", "XL" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "S", "M", "L" ] }

Remove the First Element

We can remove the first element of the array in document 1 like this:

db.products.update( 
  { _id: 1 }, 
  { $pop: { sizes: -1 } } 
)

Output:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

That message tells us that one document matched and one (i.e. the same document) was modified.

Let’s take a look at the collection now:

db.products.find()

Result:

{ "_id" : 1, "prod" : "Bat", "sizes" : [ "M", "L", "XL" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "M", "L", "XL" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "S", "M", "L" ] }

We can see that the first element of the array in document 1 has been removed.

Remove the Last Element

Now let’s remove the last element from the array in document 2:

db.products.update( 
  { _id: 2 }, 
  { $pop: { sizes: 1 } } 
)

Output:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Now let’s check the collection again:

db.products.find()

Result:

{ "_id" : 1, "prod" : "Bat", "sizes" : [ "M", "L", "XL" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "M", "L" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "S", "M", "L" ] }

We can see that the last element has been removed from the array in document 2.

Update All Documents

Here’s an example that uses the updateMany() method to update all documents:

db.products.updateMany( 
  { }, 
  { $pop: { sizes: 1 } } 
)

Output:

{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 }

And recheck the collection:

db.products.find()

Result:

{ "_id" : 1, "prod" : "Bat", "sizes" : [ "M", "L" ] }
{ "_id" : 2, "prod" : "Hat", "sizes" : [ "S", "M" ] }
{ "_id" : 3, "prod" : "Cap", "sizes" : [ "S", "M" ] }

Alternatively, you can use the update() method to update multiple documents by specifying multi: true.