$each
The $each operator is used in conjunction with other update operators, such as $push and $addToSet, to add multiple values to an array field. It allows adding multiple elements to an array in a single operation, rather than having to execute multiple update operations.
Parameters
-
value: The array of values to add to the array field.
Example (MongoDB Shell)
The following example demonstrates using the $each operator with the $push operator to add multiple elements to an array field.
Create sample documents
db.fruits.insertOne({ _id: 1, fruits: ["apple", "banana"] })
Query example
db.fruits.updateOne( { _id: 1 }, { $push: { fruits: { $each: ["cherry", "durian", "elderberry"] } } } )
View updated document
db.fruits.findOne({ _id: 1 })
Output
{
_id: 1,
fruits: [ 'apple', 'banana', 'cherry', 'durian', 'elderberry' ]
}
Code examples
To view a code example for using the $each command, choose the tab for the language that you want to use: