$each

On this page本页内容

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. $push运算符可以将$each修饰符与其他修饰符一起使用。For a list of modifiers available for $push, see Modifiers.有关$push可用的修饰符列表,请参阅修饰符

Examples示例

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

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]中的每个元素添加到文档的scores数组中,其中name字段等于joe

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

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

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

{ _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修饰符将多个元素添加到标记数组中:

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:该操作仅向tags数组添加"camera""accessories",因为该数组中已经存在"electronics"

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