MongoDB $pull Operator
MongoDB $pull operator removes all the instances of the value that matches the specified condition from the existing array within the document.
$pull Operator in MongoDB
The $pull operator in MongoDB provides a way to delete specific elements from Arryas and helps in data manipulation and customization.
It can also be used for nested arrays, making it a versatile tool.
If the $pull operator is unable to find the desired value, it returns the original array and makes no changes to it. It does not give any error or exceptions, the result will show “{ nModified: 0 }”, indicating that zero elements were modified.
Syntax
{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }
Here, <field> can specify with dot notation in embedded/nested documents or an array.
$pull Operator Examples
Let’s look at some examples of the $pull operator in MongoDB.
In the following examples, we are working with:
Database: w3wiki
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 Example
In this example, we are removing the specified elements, i.e., [“C#”, “Perl”] from the language field.
Query:
db.contributor.update({},
... {$pull: {language: {$in: ["C#", "Perl"]}}},
... {multi: true})
Removing all the elements that match the specified condition example
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”.
Query:
db.contributor.update({name: "Rohit"},
{$pull: {"personal.semesterMarks": {$lte: 75}}})
Removing elements from the array of documents example
In this example, we are removing language: “Java” and tArticles: 50 items from the array of documents, i.e., articles field.
Query:
db.contributor.update({},
... {$pull: {articles: {language: "Java", tArticles: 50}}},
... {multi: true})
Output:
KeyTakeAways About MongoDB $pull Operator
- The $pull operator in MongoDB provides a way to delete specific elements from Arrays and helps in data manipulation and customization.
- In the $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 in an array, then this operator will remove only those items in the array that match the specified <value>. Here, the order must be the same.
- If you specify a <value> in the $pull operator to remove a document, then this operator will remove only those items in the array that have the 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 requirements.
Contact Us