$pull
and $pullAll
operators are used to remove items from an array of the MongoDB document. If both of them do the same job, then what's the difference?
In this answer, we will learn the clear distinction between these operators and how to use them.
$pull
operator$pull
operator removes items from the array depending on a specific condition.
{ $pull :{<array1> : <value | condition1>,<array2> : <value | condition2>,...}}
In the syntax above, array1
and array2
represent the array names from which the items are to be removed depending on the conditions condition1
and condition2
.
$pull
operatorTo illustrate the use of $pull
operator, we will take a simple case.
Let’s create a collection named student_marks
and add marks
for the student with an id equal to 1. To perform this task, we will use insertOne()
method in the following way:
db.student_marks.insertOne({_id : 1 ,marks:[50, 40, 10, 85, 60, 94]})
Now, let's suppose that the maximum marks attained were 60. Therefore, we need to remove all marks that are greater than 60. For this, we will use the $pull
operator in the following manner:
db.student_marks.updateOne({_id : 1},{$pull :{marks : { $gt : 60 }}})
The code above finds the student_mark
document with _id
1 and removes all elements greater than 60. $gt
represents the ‘greater than’ comparison query operator. To confirm that the marks
greater than 60 have been removed, we will use the following code:
db.student_marks.find({ '_id' : 1 })
Note: Any comparison query operator can be used depending on the situation.
The aforementioned commands can be tested in the terminal below:
$pullAll
operator$pullAll
operator is used to remove items from the array by specifying them.
{ $pullAll :{<array1> : [<item1>, <item2>, ...],<array2> : [<item1>, <item2>, ...],...}}
In the syntax above, array1
and array2
represent the array names from which we will remove the items item1
and item2
.
$pullAll
operatorTo illustrate the use of $pullAll
operator, we will use a simple case.
Let's create a collection named as class
and add students
for class
with id equal to 1 (_id:1
). To perform this task, we will use the following command:
db.class.insertOne({_id : 1 ,students:['Ali', 'Huzaifa', 'Ahmed', 'Hassan']})
Now, let's suppose that Ali
and Huzaifa
have left the class. In this case, we want to remove them from class
with _id
1. For this, we will use the $pullAll
operator in the following manner:
db.class.updateOne({_id : 1},{$pullAll :{students : ['Ali' , 'Huzaifa']}})
The code above works by finding the class
document with id equal to 1 (_id:1
) and removing Ali
and Huzaifa
using $pullAll
operator. We will confirm that the desired students
have been removed using the following code:
db.class.find({ '_id':1 })
The aforementioned commands can be tested in the terminal below:
$pullAll
operator is used when we need to remove specific items from the array, whereas, $pull
operator is used to remove items that fulfill a certain condition.
Free Resources