$each
On this page本页内容
Definition定义
$each-
The$eachmodifier is available for use with the$addToSetoperator and the$pushoperator.$each修饰符可用于$addToSet运算符和$push运算符。Use with the如果$addToSetoperator 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与$pushoperator to append multiple values to an array<field>.$push运算符一起使用可将多个值附加到数组<field>。{ $push: { <field>: { $each: [ <value1>, <value2> ... ] } } }The$pushoperator can use$eachmodifier 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开始,update运算符按照字典顺序处理具有基于字符串的名称的文档字段。Fields with numeric names are processed in numeric order. 具有数字名称的字段按数字顺序处理。See Update Operators Behavior for details.有关详细信息,请参阅更新运算符行为。
Examples实例
Use $each with $push Operator使用$each和$push运算符
$each with $push OperatorThe 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:
db.students.updateOne(
{ name: "joe" },
{ $push: { scores: { $each: [ 90, 92, 85 ] } } }
)
Use $each with $addToSet Operator将$each与$addToSet运算符一起使用
$each with $addToSet OperatorA 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:已在数组中:
{
_id: 2,
item: "cable",
tags: [ "electronics", "supplies", "camera", "accessories" ]
}