MongoDB $pullAll

In MongoDB, you can use the $pullAll operator to remove all instances of the specified values from an existing array.

Use $pullAll in conjunction with a method such as update(), updateOne(), or updateMany() to update the specified document/s with the change.

Example

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 let’s say 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 ] } } 
)

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.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.

Remove Multiple Values

The argument we provided to $pullAll is an array, and so we can therefore remove multiple values by separating them with a comma.

Example:

db.foo.update( 
  { _id: 2 }, 
  { $pullAll: { bar: [ 17, 18 ] } } 
)

Output:

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

Now let’s check the collection again:

db.foo.find()

Result:

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

We can see that the values 17 and 18 have been removed from the array in document 2.

Update All Documents

You can add multi: true or use the updateMany() method to update all documents that match the criteria.

When you do this, remove any selection criteria from the first query document (that specifies which document/s to update). In other words, use an empty document as the first argument to the update() (or updateMany()) method.

Example:

db.foo.update( 
  { }, 
  { $pullAll: { bar: [ 1, 8 ] } },
  { multi: true }
)

Output:

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

In this case, we can see that three documents matched (because there are three documents in the collection), and all three were modified (because they all contained the specified values).

Let’s check the collection again:

db.foo.find()

Result:

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

We can see that all instances have been updated as specified.