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: GeeksforGeeks
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.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Sumit"}, 
... {$addToSet: {language: {$each: ["Ruby", "Java", "C", "C#"]}}})

chevron_right


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.

filter_none

edit
close

play_arrow

link
brightness_4
code

db.contributor.update({name: "Rohit"}, 
... {$push: {language: {$each: ["Java", "C", "Python"]}}})

chevron_right


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.