Skip to content
Related Articles

Related Articles

MongoDB – $pull Operator
  • Last Updated : 10 May, 2020

MongoDB provides different types of array update operators to update the values of the array fields in the documents and $pull operator is one of them. This operator is used to remove all the instances of the value or the value that matches the specified condition from the existing array.

Syntax:

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

Here, <field> can specify with dot notation in embedded/nested documents or an array.

  • In $pull operator, if you specify the <condition> and the array contains the embedded/nested documents, then this operator applies the <condition> as if each array item were a document in a collection.
  • If you specify a <value> in the $pull operator to remove is an array, then this operator will remove only those items in the array that match the specified <value>. Here, the order must be same.
  • If you specify a <value> in the $pull operator to remove is a document, then this operator will remove only those items in the array that have exact same fields and values. Here, the order of the fields can differ.
  • You can use this operator with methods like update(), findAndModify(), etc., according to your requirement.

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 all the elements that equal to the specified value:

In this example, we are removing the specified elements, i.e., [“C#”, “Perl”] from the language field.




db.contributor.update({},
... {$pull: {language: {$in: ["C#", "Perl"]}}},
... {multi: true})

Removing all the elements that match the specified condition:

In this example, we are removing semester marks that are less than and equal to ($lte) 73 from the personal.semesterMarks field in the document that matches the specified condition, i.e., name: “Rohit”.




db.contributor.update({name: "Rohit"}, 
                      {$pull: {"personal.semesterMarks": {$lte: 75}}})

Removing elements from the array of documents:

In this example, we are removing language: “Java” and tArticles: 50 items from the array of documents, i.e., articles field.




db.contributor.update({}, 
... {$pull: {articles: {language: "Java", tArticles: 50}}}, 
... {multi: true})


Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :