MongoDB – $pullAll Operator

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 $pull operator, $pull operator removes items by specifying a query, whereas $pullAll operator removes items that matches the listed values. You can use this operator with methods like update(), findAndModify(), etc., according to your requirement.

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.

In the following examples, we are working with:



Database: GeeksforGeeks
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs.

Removing items from an array using $pullAll operator:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Removing items from an array in the embedded document using $pullAll operator:

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.