On this page本页内容
$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
可用的修饰符列表,请参阅修饰符。
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.有关详细信息,请参阅更新运算符行为。
$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 ] } } } )
$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" ] }