3 Ways to Remove a Value from an Array in MongoDB

MongoDB provides a few operators that enable you to remove values from arrays.

These include:

  • $pull
  • $pullAll
  • $pop

The $pull Operator

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

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

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

We can remove an element from the array in document 1 like this:

db.products.update( 
  { _id: 1 }, 
  { $pull: { sizes: "XXL" } } 
)

Now when we check the collection, we can see that XXL has been removed from document 1 as specified:

db.products.find()

Result:

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

The $pullAll Operator

The $pullAll operator removes all instances of the specified values from the array.

Suppose we have a collection with the following documents:

{ "_id" : 1, "bar" : [ 1, 7, 2, 3, 8, 7, 1 ] }
{ "_id" : 2, "bar" : [ 0, 1, 8, 17, 18, 8 ] }
{ "_id" : 3, "bar" : [ 15, 11, 8, 0, 1, 3 ] }

And we want to remove all values of 7 from the array in document 1.

We can do this:

db.foo.update( 
  { _id: 1 }, 
  { $pullAll: { bar: [ 7 ] } } 
)

This removes both occurrences of 7 from the array in document 1.

We can verify this by checking the collection:

db.foo.find()

Result:

{ "_id" : 1, "bar" : [ 1, 2, 3, 8, 1 ] }
{ "_id" : 2, "bar" : [ 0, 1, 8, 17, 18, 8 ] }
{ "_id" : 3, "bar" : [ 15, 11, 8, 0, 1, 3 ] }

We can see that the array in document 1 has had all its 7 values removed as specified.

While $pullAll is similar to $pull, the difference is that $pullAll removes elements that match the listed values. This is unlike $pull, where you remove values by specifying a query.

The $pop Operator

The $pop operator removes the first or last element of an array.

Provide a value of -1 to remove the first element, and 1 to remove the last.

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

{ "_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" ] }

The following code removes the last element from the array in document 1:

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

We can verify this by checking the collection:

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" ] }