$pullAll Operator in MongoDB: Remove Elements from an Array Within Documents

One of the most popular database management services available especially for Node.js is MongoDB, which includes an expansive range of advanced tools.  An application that uses such a powerful database system can include a wide range of features and functionalities. Furthermore, enhanced security functions can be implemented. 

A MongoDB database allows you to build applications that are capable of doing a lot more than CRUD functions. In addition to supporting querying, printing, and changing data, the database also offers a variety of operators. Regardless of the level of experience which its users possess, MongoDB has something to offer.

In this article, we will see another special MongoDB operator $pullAll, and its syntax and demonstrate it with examples. Let’s get started.

Also Read: $pull Operator in MongoDB

MongoDB $pullAll Operator

In MongoDB, we usually use the delete() or deleteMany() function to delete values from the documents, but you want to delete a particular element from an array within a field. It can be done by using dot notation to reach to that element but the process even gets complex when you want to delete multiple elements. Here comes the $pullAll operator.

The $pullAll operator is an operator that works on arrays. We can use this operator to remove all instances of given values from the specified array field.

The $pullAll operator is almost similar to the $pull operator. It can be used with all update operation functions like update(), findAndModify() and more.

Syntax of MongoDB $pullAll Operator

Below is the syntax of the MongoDB $pullAll operator.

Syntax:

db.collection.updateMany({}, { $pullAll: { field1: [ value1, value2 ... ], ... } } })

Parameters:

  1. Here “collection” is the collection name where we are looking for the documents.
  2. “updateMany()” is the method we are using to update the documents.
  3. In “{ field1: [ value1, value2 … ], … }”, the field represents an array field within the documents, and [ value 1, value 2 …. ] are the elements we want to remove from that array field.

Note:

In the above syntax, we have used updateMany(), which you can change to update(), findAndModify() etc. accordingly. Since we want to remove elements from the array field from each document, we have used updateMany().

Removing Elements from Array Fields Using the $pullAll Operator

Let us now look at some practical examples of using the $pullAll operator to remove elements or items from an array field in MongoDB.

Setup:

1. Start the MongoDB shell.

2. Execute the following commands to list all the available databases & move into one of them.

show dbs
use droneVerse

Here we are using the “droneVerse” database where we have already created a collection “drones” having documents containing an array field so that we can demonstrate removing elements using the $pullAll operator.

3. Execute the below query to display documents from a collection.

> db.drones.find({}).pretty()
{
        "_id" : ObjectId("615dfce7f1ce6040485ecf62"),
        "utility" : [
                "Monitoring or Inspection"
        ],
        "onSale" : false,
        "name" : "RQ – Ariela Blingdom",
        "price" : 28000,
        "weight" : "3.4 kilograms",
        "additionalDetails" : {
                "material" : "polystyrene",
                "moreUses" : [
                        "Photography",
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615dff74f1ce6040485ecf63"),
        "utility" : [
                "Monitoring or Inspection",
                "Photography"
        ],
        "onSale" : true,
        "name" : "T5 – Doom Glancer",
        "price" : 8000,
        "weight" : "4 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Land Inspection",
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615dff94f1ce6040485ecf64"),
        "utility" : [
                "Security",
                "Photography"
        ],
        "onSale" : true,
        "name" : "TumblE – Jumper",
        "price" : 18000,
        "weight" : "5.6 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection",
                        "Videography"
                ]
        }
}
{
        "_id" : ObjectId("615dffb0f1ce6040485ecf65"),
        "utility" : [
                "Monitoring or Inspection",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "Mount Hike Drone",
        "price" : 9000,
        "weight" : "7 kilograms",
        "additionalDetails" : {
                "material" : "aluminium",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("615dffc8f1ce6040485ecf66"),
        "utility" : [
                "Security",
                "Recreation"
        ],
        "onSale" : false,
        "name" : "Defender Martial X55",
        "price" : 12000,
        "weight" : "9.1 kilograms",
        "additionalDetails" : {
                "material" : "alumnium",
                "moreUses" : [
                        "Security",
                        "Combat"
                ]
        }
}

Removing Elements from Array Fields

Let’s now try to use the $pullAll operator and specify some elements to be removed from the “utility” array field from the above documents.

Below is the query for that:

> db.drones.updateMany({}, {$pullAll: {utility: ["Monitoring or Inspection", "Recreation", "Security"]}})

{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 5 }

Let’s see what our documents look like after the $pullAll operation:

> db.drones.find({}).pretty()
{
        "_id" : ObjectId("615dfce7f1ce6040485ecf62"),
        "utility" : [ ],
        "onSale" : false,
        "name" : "RQ – Ariela Blingdom",
        "price" : 28000,
        "weight" : "3.4 kilograms",
        "additionalDetails" : {
                "material" : "polystyrene",
                "moreUses" : [
                        "Photography",
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615dff74f1ce6040485ecf63"),
        "utility" : [
                "Photography"
        ],
        "onSale" : true,
        "name" : "T5 – Doom Glancer",
        "price" : 8000,
        "weight" : "4 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Land Inspection",
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615dff94f1ce6040485ecf64"),
        "utility" : [
                "Photography"
        ],
        "onSale" : true,
        "name" : "TumblE – Jumper",
        "price" : 18000,
        "weight" : "5.6 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Water Inspection",
                        "Videography"
                ]
        }
}
{
        "_id" : ObjectId("615dffb0f1ce6040485ecf65"),
        "utility" : [ ],
        "onSale" : false,
        "name" : "Mount Hike Drone",
        "price" : 9000,
        "weight" : "7 kilograms",
        "additionalDetails" : {
                "material" : "aluminium",
                "moreUses" : [
                        "Land Inspection",
                        "Water Inspection"
                ]
        }
}
{
        "_id" : ObjectId("615dffc8f1ce6040485ecf66"),
        "utility" : [ ],
        "onSale" : false,
        "name" : "Defender Martial X55",
        "price" : 12000,
        "weight" : "9.1 kilograms",
        "additionalDetails" : {
                "material" : "alumnium",
                "moreUses" : [
                        "Security",
                        "Combat"
                ]
        }
}

In the result we got, the most of documents are now left blank and some are left with values that we did not wish to remove indicating that the operation is successfully performed on the specified array field.

Removing Elements from Nested Array Fields

Let’s now try to remove elements in the nested array fields.

Nested array fields here mean the array from which we want to remove elements is inside a nested document, i.e., the document that is inside the main document.

In simple words, we have documents that contain subdocuments and within those subdocuments, we have arrays from which we want to remove elements. For this, we will have to get to the array by passing the appropriate path as an argument in place of the field name.

Below is the query for that:

> db.drones.updateMany({}, {$pullAll: {"additionalDetails.moreUses": ["Land Inspection", "Combat", "Water Inspection"]}})

{ "acknowledged" : true, "matchedCount" : 5, "modifiedCount" : 4 }

Let’s see what our documents look like after the $pullAll operation:

> db.drones.find({}).pretty()
{
        "_id" : ObjectId("615dfce7f1ce6040485ecf62"),
        "utility" : [ ],
        "onSale" : false,
        "name" : "RQ – Ariela Blingdom",
        "price" : 28000,
        "weight" : "3.4 kilograms",
        "additionalDetails" : {
                "material" : "polystyrene",
                "moreUses" : [
                        "Photography",
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615dff74f1ce6040485ecf63"),
        "utility" : [
                "Photography"
        ],
        "onSale" : true,
        "name" : "T5 – Doom Glancer",
        "price" : 8000,
        "weight" : "4 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Security"
                ]
        }
}
{
        "_id" : ObjectId("615dff94f1ce6040485ecf64"),
        "utility" : [
                "Photography"
        ],
        "onSale" : true,
        "name" : "TumblE – Jumper",
        "price" : 18000,
        "weight" : "5.6 kilograms",
        "additionalDetails" : {
                "material" : "lithium",
                "moreUses" : [
                        "Videography"
                ]
        }
}
{
        "_id" : ObjectId("615dffb0f1ce6040485ecf65"),
        "utility" : [ ],
        "onSale" : false,
        "name" : "Mount Hike Drone",
        "price" : 9000,
        "weight" : "7 kilograms",
        "additionalDetails" : {
                "material" : "aluminium",
                "moreUses" : [ ]
        }
}
{
        "_id" : ObjectId("615dffc8f1ce6040485ecf66"),
        "utility" : [ ],
        "onSale" : false,
        "name" : "Defender Martial X55",
        "price" : 12000,
        "weight" : "9.1 kilograms",
        "additionalDetails" : {
                "material" : "alumnium",
                "moreUses" : [
                        "Security"
                ]
        }
}

In the result we got, the nested array fields of some documents become empty and the remaining do not contain the elements we specified in the $pullAll operator indicating that the operation is successfully performed on the nested array field.

Conclusion

In this article, we have learned about the MongoDB $pullAll operator used to remove elements from Array Fields. We have also given you a separate description of how to use this operator on the Nested Array Field as well.

Using the $pullAll operator is easy and straightforward, you just have to pass the array field as a key and the array containing elements to be removed as a value. You can clubed it with methods like updateMany(), update(), findAndModify(), etc to get the operation done. We hope after reading this article you find all the answers to your question.

Read More: 

Reference

$pullAll – MongoDB Manual

Aneesha S
Aneesha S
Articles: 172