Database Manual / Reference / Query Language / Update / Arrays

$each

Definition定义

$each

The $each modifier is available for use with the $addToSet operator and the $push operator.$each修饰符可与$addToSet运算符和$push运算符一起使用。

Use with the $addToSet operator to add multiple values to an array <field> if the values do not exist in the <field>.如果数组<field>中不存在多个值,则使用$addToSet运算符将这些值添加到数组<field>中。

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

Use with the $push operator to append multiple values to an array <field>.$push运算符一起使用,可以将多个值附加到数组<field>中。

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

The $push operator can use $each modifier with other modifiers. For a list of modifiers available for $push, see Modifiers.$push运算符可以将$each修饰符与其他修饰符一起使用。有关可用于$push的修饰符列表,请参阅修饰符

Behavior行为

Starting in MongoDB 5.0, update operators process document fields with string-based names in lexicographic order. Fields with numeric names are processed in numeric order. See Update Operators Behavior for details.从MongoDB 5.0开始,更新运算符按字典顺序处理具有基于字符串的名称的文档字段。具有数字名称的字段按数字顺序处理。有关详细信息,请参阅更新运算符行为

Examples示例

Use $each with $push Operator$each$push运算符一起使用

The following example appends each element of [ 90, 92, 85 ] to the scores array for the document where the name field equals joe:以下示例将[90,92,85]的每个元素附加到name字段等于joe的文档的scores数组中:

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

Use $each with $addToSet Operator使用$each$addToSet运算符

A collection inventory has the following document:集合inventory包含以下文档:

db.inventory.insertOne (
{ _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:然后,以下操作使用$addToSet运算符和$each修饰符向tags数组添加多个元素:

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

The operation only adds "camera" and "accessories" to the tags array. "electronics" was already in the array:该操作仅将"camera""accessories"添加到tags数组中。"electronics"已经在数组中:

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