MongoDB – $each Modifier
MongoDB provides different types of array update operators to update the values of the array fields in the documents and $each modifier is one of them. This modifier is used to append multiple values to the array field. You can use this modifier with $addToSet
and $push
operators:
$each
modifier with $addToSet
operator –
If you use $each
modifier with $addToSet
operator, then it adds multiple values to an array field if the specified value does not present in the array field.
Syntax:
{ $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } }
$each
modifier with $push
operator –
If you use $each modifier with $push operator, then it appends multiple values to an array field. The $push operator is allowed to use $each modifier with other modifiers ( like, $slice
, $sort
, and $position
).
Syntax:
{ $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }
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.
Using $each modifier with $addToSet operator:
In this example, we are updating a contributor’s document whose name is Sumit using $each
modifier with $addToSet
operator. Here, this operation only adds “Ruby” and “C” in the language field and does not add “Java”, “C#” because they already exists in the language field.
db.contributor.update({name: "Sumit" }, ... {$addToSet: {language: {$each: [ "Ruby" , "Java" , "C" , "C#" ]}}}) |
Using $each modifier with $push operator:
In this example, we are updating a contributor’s document whose name is Rohit using $each
modifier with $push
operator. Here, this operation appends the specified value, i.e., [“Java”, “C”, “Python”] to the end of the language field. It does not remove duplicate values.
db.contributor.update({name: "Rohit" }, ... {$push: {language: {$each: [ "Java" , "C" , "Python" ]}}}) |
Contact Us