$pull Operator in MongoDB: Removing Elements from Arrays

MongoDB provides a variety of operators that are suitable for various purposes such as aggregation pipeline, text search, geospatial query, array manipulation, etc. They are highly advanced, flexible, and easy to understand, allowing applications built on MongoDB to perform tasks beyond basic CRUD operations. This is undoubtedly one of the reasons why MongoDB is so widely used and popular. It appeals to novices and seasoned developers alike, regardless of their experience level.

In this article, we will learn about another most used and useful operator which is $pull. We will demonstrate examples to see how you can use the $pull operator in MongoDB. So, let’s start.

MongoDB $pull Operator

The $pull operator is used to remove all instances of a value or values from a given array, that match a specified condition. It can be used with updateOne() and updateMany() methods, as well as with the update() method in MongoDB.

When the value specified to remove is an array, the $pull operator removes all the elements that match the value, inside that array. It also preserves the same order.

If the value specified to remove is a document, then the $pull operator removes only those elements in the array, whose fields and values match the entire specified document. The order of the fields within the document does not matter, it searches for an exact match of the entire document to determine which elements to remove. 

Syntax:

Below is the syntax for using the $pull operator in MongoDB.

{ $pull: { field1: value|condition, field2: value|condition, ... } }

Parameters:

  • feildN is the array field from which the elements will be removed,
  • value|condition is used to decide which elements in the array should be removed.

Return:

This operator is basically used by updateOne() and updateMany() methods and returns details about the update operation performed. The structure of the object depends upon the MongoDB driver being used.

Error:

This operator can throw errors due to non-existent fields, type mismatches (only arrays are allowed), invalid conditions, and write concern issues.

Removing Elements Within Array Using $pull Operator

Below are the step for using the $pull operator to remove all items from all documents inside a collection, whose values match the given value:

  • Start the MongoDB server.
  • Choose the database you want to work and move into it:
show dbs
use apparelStore
  • Next, let’s see what documents we have in a particular collection:

Here we will be using the find() method to get all the documents inside the outfits collection which we have already created. Each document in this collection has arrays containing elements.

> db.outfits.find( { } )

{
   _id: 1000,
   tops: [ "tank", "crop", "cami", "maxi", "tube" ],
   pants: [ "sweatpants", "harem", "bell bottoms", "culottes" ]
}
{
   _id: 2000,
   tops: [ "tank", "turtle neck", "cami", "blouse", "sweater" ],
   pants: [ "jeans", "harem", "bell bottoms", "chinos" ]
}
{
   _id: 3000,
   tops: [ "peplum", "crop", "cami", "maxi", "off-shoulder" ],
   pants: [ "cargo", "harem", "joggers", "chinos" ]
}
{
   _id: 4000,
   tops: [ "batwing", "peplum", "boxy", "maxi", "tube" ],
   pants: [ "palazzo", "track pants", "bell bottoms", "culottes" ]
}
{
   _id: 5000,
   tops: [ "tshirt", "crop", "v-neck", "turtle neck", "tube" ],
   pants: [ "sweatpants", "chinos", "jodhpurs", "corduroy trousers" ]
}
  • Let’s say we are no longer selling chinos, cami, and bell bottoms in any of our stores. This is where we will need to use the $pull operator to remove all the items that match our given value from all our documents.
> db.outfits.updateMany(
    { },
    { $pull: { tops: "cami", pants: { $in: [ "chinos", "bell bottoms" ] } },
    { multi: true }
)

This code should now remove “cami” from the “tops” field and “chinos” and “bell bottoms” from the “pants” fields.

  • Let’s verify the operation using the find() method again:
> db.outfits.find( { } )

{
   _id: 1000,
   tops: [ "tank", "crop", "maxi", "tube" ],
   pants: [ "sweatpants", "harem", "culottes" ]
}
{
   _id: 2000,
   tops: [ "tank", "turtle neck", "blouse", "sweater" ],
   pants: [ "jeans", "harem" ]
}
{
   _id: 3000,
   tops: [ "peplum", "crop", "maxi", "off-shoulder" ],
   pants: [ "cargo", "harem", "joggers" ]
}
{
   _id: 4000,
   tops: [ "batwing", "peplum", "boxy", "maxi", "tube" ],
   pants: [ "palazzo", "track pants", "culottes" ]
}
{
   _id: 5000,
   tops: [ "tshirt", "crop", "v-neck", "turtle neck", "tube" ],
   pants: [ "sweatpants", "jodhpurs", "corduroy trousers" ]
}

In the resulting output, you can see that the specified value no longer exists, so the operation is considered to have been completed successfully.

Removing Documents Within Array Using $pull Operator

Let us now learn how to remove matched elements from an array of documents.

  • For this, we will be using the survey collection having the following documents:
{
   _id: 1,
   results: [
      { item: "A", score: 5 },
      { item: "B", score: 8, comment: "Strongly agree" }
   ]
}
{
   _id: 2,
   results: [
      { item: "C", score: 8, comment: "Strongly agree" },
      { item: "B", score: 4 }
   ]
}
  • Let’s try to remove all array elements that contain both a score field equal to 8 and an item field equal to “B”:
db.survey.update(
  { },
  { $pull: { results: { score: 8 , item: "B" } } },
  { multi: true }
)
  • Take a look at what the documents look like after this operation:
{
   "_id" : 1,
   "results" : [ { "item" : "A", "score" : 5 } ]
}
{
  "_id" : 2,
  "results" : [
      { "item" : "C", "score" : 8, "comment" : "Strongly agree" },
      { "item" : "B", "score" : 4 }
   ]
}

The resulting array does not contain a score field with the value “8” and an item field with the value “B”, that was in the existing array.

Also Read: Querying Embedded Documents in MongoDB

Conclusion

In this article, we have learned that by using the $pull operator we can modify an array by pulling out certain elements that match the specified condition. We have also demonstrated an example of removing documents from arrays of documents using this operator. We have used updateMany() method with $pull to update multiple arrays, if you want to read about it, check out: Update Multiple Documents using updateMany() in MongoDB

References

Aneesha S
Aneesha S
Articles: 172