Introduction to MongoDB $pullAll Operator

The $pullAll operator in MongoDB is used to remove all elements in an array that match a specified value. Similar to the $pull operator, but $pull only removes one matching item while $pullAll can remove multiple matching items.

Syntax

The syntax for the $pullAll operator is as follows:

{ $pullAll: { <field1>: [ <value1>, <value2>, ... ], ... } }

where <field> is the array field name to be operated on, and <value> is the value to be removed from the array. Multiple fields can be used in the same operation.

Use Cases

The $pullAll operator is useful for situations where multiple matching items need to be removed from an array. For example, a document contains a user’s list of friends, and the user wants to remove multiple friends from the list. Using the $pullAll operator can easily remove all specified friends.

Examples

Suppose there is a collection named users that contains the following document:

{
    _id: 1,
    friends: ['Alice', 'Bob', 'Charlie', 'David', 'Emily']
}

Now the user decides to remove three friends, Bob, David, and Emily. This can be done with the following command:

db.users.update(
  { _id: 1 },
  { $pullAll: { friends: ["Bob", "David", "Emily"] } }
)

After executing the above command, the values in the friends array will become ['Alice', 'Charlie']. Because the $pullAll operator can remove multiple matching items at once, it is very suitable for this situation.

Next, suppose we have a collection named students that contains the following document:

{
    _id: 1,
    grades: [
        { grade: 'A', score: 95 },
        { grade: 'B', score: 80 },
        { grade: 'C', score: 70 },
        { grade: 'A', score: 90 }
    ]
}

Now we want to remove all documents in the grades array with scores lower than 80. This can be done with the following command:

db.students.update(
  { _id: 1 },
  {
    $pullAll: {
      grades: [
        { grade: "B", score: 80 },
        { grade: "C", score: 70 }
      ]
    }
  }
)

After executing the above command, the values in the grades array will become:

{ grade: 'A', score: 95 }
{ grade: 'A', score: 90 }

Conclusion

The $pullAll operator can conveniently remove multiple matching items from an array and is suitable for situations where multiple values need to be removed.