$each

Definition

  • $each
  • The $each modifier is available for use with the$addToSet operator and the $pushoperator.

Use with the $addToSet operator to add multiple values toan array <field> if the values do not exist in the <field>.

  1. { $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } } }

Use with the $push operator to append multiple values toan array <field>.

  1. { $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }

The $push operator can use $each modifier withother modifiers. For a list of modifiers available for$push, see Modifiers.

Examples

Use $each with $push Operator

The following example appends each element of [ 90, 92, 85 ] tothe scores array for the document where the name fieldequals joe:

  1. db.students.update(
  2. { name: "joe" },
  3. { $push: { scores: { $each: [ 90, 92, 85 ] } } }
  4. )

Use $each with $addToSet Operator

A collection inventory has the following document:

  1. { _id: 2, item: "cable", tags: [ "electronics", "supplies" ] }

Then the following operation uses the $addToSet operatorwith the $each modifier to add multiple elements to thetags array:

  1. db.inventory.update(
  2. { _id: 2 },
  3. { $addToSet: { tags: { $each: [ "camera", "electronics", "accessories" ] } } }
  4. )

The operation adds only "camera" and "accessories" to thetags array since "electronics" already exists in the array:

  1. {
  2. _id: 2,
  3. item: "cable",
  4. tags: [ "electronics", "supplies", "camera", "accessories" ]
  5. }