$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可用的修饰符列表,请参阅修饰符

Behavior行为

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

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

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具有以下文档:

{ _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. 该操作仅将"camera""accessories"添加到tags数组中。"electronics" was already in the array:"electronics"已经在数组中:

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