Open In App

MongoDB – $pull Operator

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 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})


Article Tags :