OPTIONS
翻译或纠错本页面

$each

$each

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

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

db.collection.update( <query>,
                      {
                        $addToSet: { <field>: { $each: [ <value1>, <value2> ... ] } }
                      }
                    )

Use the $each modifier with the $push operator to append multiple values to an array <field>.

db.collection.update( <query>,
                      {
                        $push: { <field>: { $each: [ <value1>, <value2> ... ] } }
                      }
                    )

在 2.4 版更改: MongoDB adds support for the $each modifier to the $push operator. The $push operator can use $each modifier with other modifiers. See $push for details.

Examples

Use $each with $push Operator

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

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

Use $each with $addToSet Operator

A collection inventory has the following document:

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

Then the following operation uses the $addToSet operator with the $each modifier to add multiple elements to the tags array:

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

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

{ _id: 2,
  item: "cable",
  tags: [  "electronics",  "supplies",  "camera",  "accessories" ] }
←   $push $slice  →