$pull
-
$pull
-
The
$pull
operator removes from an existing array all instances of a value or values that match a specified condition.The
$pull
operator has the form:To specify a
<field>
in an embedded document or in an array, use dot notation.
Behavior
If you specify a <condition>
and the array elements are embedded documents, $pull
operator applies the <condition>
as if each array element were a document in a collection. See Remove Items from an Array of Documents for an example.
If the specified <value>
to remove is an array, $pull
removes only the elements in the array that match the specified <value>
exactly, including order.
If the specified <value>
to remove is a document, $pull
removes only the elements in the array that have the exact same fields and values. The ordering of the fields can differ.
Examples
Remove All Items That Equal a Specified Value
Given the following document in the stores
collection:
The following operation updates all documents in the collection to remove "apples"
and "oranges"
from the array fruits
and remove "carrots"
from the array vegetables
:
After the operation, the fruits
array no longer contains any "apples"
or "oranges"
values, and the vegetables
array no longer contains any "carrots"
values:
Remove All Items That Match a Specified $pull
Condition
Given the following document in the profiles
collection:
The following operation will remove all items from the votes
array that are greater than or equal to ($gte
) 6
:
After the update operation, the document only has values less than 6:
Remove Items from an Array of Documents
A survey
collection contains the following documents:
The following operation will remove from the results
array all elements that contain both a score
field equal to 8
and an item
field equal to "B"
:
The $pull
expression applies the condition to each element of the results
array as though it were a top-level document.
After the operation, the results
array contains no documents that contain both a score
field equal to 8
and an item
field equal to "B"
.
Because $pull
operator applies its query to each element as though it were a top-level object, the expression did not require the use of $elemMatch
to specify the condition of a score
field equal to 8
and item
field equal to "B"
. In fact, the following operation will not pull any element from the original collection.
However, if the survey
collection contained the following documents, where the results
array contains embedded documents that also contain arrays:
Then you can specify multiple conditions on the elements of the answers
array with $elemMatch
:
The operation removed from the results
array those embedded documents with an answers
field that contained at least one element with q
equal to 2
and