Open In App

MongoDB – $pullAll Operator

Last Updated : 24 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

MongoDB $pullAll operator is a crucial tool for efficiently managing arrays within MongoDB documents. It allows users to remove all instances of specified values from an array and provides a direct way to update array fields. In this article, We will learn about the MongoDB $pullAll Operator by understanding various examples in detail.

MongoDB $pullAll Operator

  • The MongoDB $pullAll operator is used to remove all instances of the specified values from an array.
  • MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pullAll operator is one of them.
  • This operator is used to remove all instances of the specified values from an existing array. It is different from the $pull operator.
  • $pull operator removes items by specifying a query, whereas $pullAll operator removes items that match the listed values. We can use this operator with methods like update(), findAndModify(), etc. according to our requirements.

Syntax:

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

Here, field can specify with dot notation in embedded/nested documents or an array and if value is an array or a document, then $pullAll operator will remove only those items in the array that match the specified value.

Note: The $pullAll operator will remove items from the array in the same order in which they are specified in the value.

Examples of MongoDB $pullAll

We will use the contributor collection on which we will perform various examples are shown below:

Example 1: Removing items from an array

In this example, we are removing items specified in the list, i.e., [“Java”, “C#”, “Python”] from the language field with the help of $pullAll operator.

db.contributor.update({name: "Rohit"},
{$pullAll: {language: ["Java", "C#", "Python"]}})

Output:

Example 2: Removing items from an array in the embedded document

In this example, we are removing items specified in the list, i.e., [71, 72] from the personal.semesterMarks field with the help of $pullAll operator.

db.contributor.update({name: "Sumit"},
{$pullAll: {"personal.semesterMarks": [71, 72]}})

Output:

pullall-example-2

Conclusion

The $pullAll operator in MongoDB provides a convenient way to remove multiple specified values from an array field in documents. Its straightforward syntax and ability to remove items directly based on their values make it a valuable tool for array manipulation in MongoDB updates.


Next Article

Similar Reads