0
0
MongodbHow-ToBeginner · 3 min read

How to Use $each in MongoDB: Syntax and Examples

In MongoDB, $each is used with the $push update operator to add multiple elements to an array in a single operation. It allows you to specify an array of values to append instead of adding one element at a time.
📐

Syntax

The $each operator is used inside the $push update operator to add multiple values to an array field. The basic syntax is:

  • { $push: { arrayField: { $each: [value1, value2, ...] } } }

Here, arrayField is the name of the array you want to update, and the $each operator takes an array of values to add.

json
{
  $push: {
    arrayField: {
      $each: [value1, value2, value3]
    }
  }
}
💻

Example

This example shows how to add multiple tags to a document's tags array using $each. It updates the document with _id: 1 by pushing three new tags at once.

mongodb
db.products.updateOne(
  { _id: 1 },
  {
    $push: {
      tags: {
        $each: ["red", "blue", "green"]
      }
    }
  }
);
Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
⚠️

Common Pitfalls

One common mistake is trying to use $each without $push, which will cause an error because $each only works as a modifier inside $push or $addToSet. Another pitfall is forgetting that $each expects an array of values, so passing a single value without wrapping it in an array will not work as intended.

Wrong usage example:

{ $each: "red" }

Correct usage example:

{ $each: ["red"] }
mongodb
/* Wrong: */
db.collection.updateOne(
  { _id: 1 },
  { $push: { tags: { $each: "red" } } }
);

/* Right: */
db.collection.updateOne(
  { _id: 1 },
  { $push: { tags: { $each: ["red"] } } }
);
📊

Quick Reference

OperatorPurposeUsage Example
$pushAdd element(s) to an array{ $push: { arr: value } }
$eachAdd multiple elements inside $push{ $push: { arr: { $each: [val1, val2] } } }
$addToSetAdd unique element(s) to an array{ $addToSet: { arr: value } }
$each with $addToSetAdd multiple unique elements{ $addToSet: { arr: { $each: [val1, val2] } } }

Key Takeaways

Use $each inside $push to add multiple values to an array in one update.
$each requires an array of values, even if adding a single element.
Never use $each alone; it must be combined with $push or $addToSet.
Using $each improves efficiency by reducing multiple update calls.
Remember $addToSet with $each adds unique values only, avoiding duplicates.