$each

在本页面

Definition

如果<field>中不存在值,请与$addToSet运算符配合使用,以将多个值添加到数组<field>中。

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

$push运算符一起使用,可将多个值附加到数组<field>

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

$push运算符可以与其他修饰符一起使用$each修饰符。有关$push可用的修饰符的列表,请参见Modifiers

Examples

将$ each 与$ push 运算符配合使用

下面的示例将name字段等于joe的文档的[ 90, 92, 85 ]的每个元素追加到scores数组:

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

将$ each 与$ addToSet 运算符配合使用

集合inventory包含以下文档:

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

然后,以下操作将$addToSet运算符与$each修饰符结合使用,以将多个元素添加到tags数组中:

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

该操作仅将"camera""accessories"添加到tags数组中,因为"electronics"已存在于该数组中:

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