$addToSet

On this page本页内容

Definition定义

$addToSet

The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array.$addToSet运算符将值添加到数组中,除非该值已经存在,在这种情况下,$addToSet对该数组不做任何操作。

The $addToSet operator has the form:$addToSet运算符的形式如下:

{ $addToSet: { <field1>: <value1>, ... } }

To specify a <field> in an embedded document or in an array, use dot notation.要在嵌入文档或数组中指定<field>,请使用点表示法

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.有关详细信息,请参阅更新运算符行为

$addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. 仅确保不会向集合中添加重复项,并且不会影响现有重复元素。$addToSet does not guarantee a particular ordering of elements in the modified set.不保证修改集合中元素的特定顺序。

Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $addToSet with an empty operand expression ( { } ). 从MongoDB 5.0开始,当使用带有空操作数表达式({ })的更新运算符(如$addToSet)时,mongod不再引发错误。An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).空更新不会导致任何更改,也不会创建oplog条目(这意味着该操作是无操作)。

Missing Field缺失字段

If you use $addToSet on a field that is absent from the document to update, $addToSet creates the array field with the specified value as its element.如果对文档中不存在的字段使用$addToSet进行更新,$addToSet将创建具有指定值作为其元素的数组字段。

Field is Not an Array字段不是数组

If you use $addToSet on a field that is not an array, the operation will fail.如果对不是数组的字段使用$addToSet,则操作将失败。

For example, create the pigments collection:例如,创建pigments集合:

db.pigments.insertOne( { _id: 1, colors: "blue, green, red" } )

The colors field is not an array. colors字段不是数组。The following $addToSet operation fails:以下$addToSet操作失败:

db.pigments.updateOne(
   { _id: 1 },
   { $addToSet: { colors: "mauve" } }
)

Value to Add is An Array要添加的值是数组

If the value is an array, $addToSet appends the whole array as a single element.如果值是一个数组,$addToSet将整个数组作为单个元素附加。

Create the alphabet collection:创建alphabet集合:

db.alphabet.insertOne( { _id: 1, letters: ["a", "b"] } )

The following operation appends the array [ "c", "d" ] to the letters field:以下操作将数组[ "c", "d" ]附加到字母字段:

db.alphabet.updateOne(
   { _id: 1 },
   { $addToSet: { letters: [ "c", "d" ] } }
)

The array [ "c", "d" ] is added as a single element:数组[ "c", "d" ]作为单个元素添加:

{ _id: 1, letters: [ 'a', 'b', [ 'c', 'd' ] ] }
Tip提示

To add each element of the value separately, use the $each modifier with $addToSet. 单独添加值的每个元素,请使用$addToSet$each修饰符。See $each Modifier for details.有关详细信息,请参阅$each修饰符

Value to Add is a Document要添加的值是文档

If the value is a document, MongoDB determines that the document is a duplicate if an existing document in the array matches the to-be-added document exactly; i.e. the existing document has the exact same fields and values and the fields are in the same order. 如果该值为文档,则如果数组中的现有文档与要添加的文档完全匹配,则MongoDB将确定该文档为重复文档;即,现有文档具有完全相同的字段和值,并且字段顺序相同。As such, field order matters and you cannot specify that MongoDB compare only a subset of the fields in the document to determine whether the document is a duplicate of an existing array element.因此,字段顺序很重要,您不能指定MongoDB只比较文档中的字段子集,以确定文档是否是现有数组元素的副本。

Examples示例

Create the inventory collection:创建inventory集合:

db.inventory.insertOne(
   { _id: 1, item: "polarizing_filter", tags: [ "electronics", "camera" ] }
)

Add to Array添加到数组

The following operation adds the element "accessories" to the tags array since "accessories" does not exist in the array:以下操作将元素"accessories"添加到tags数组中,因为"accessories"在数组中不存在:

db.inventory.updateOne(
   { _id: 1 },
   { $addToSet: { tags: "accessories" } }
)

Value Already Exists值已存在

The following $addToSet operation has no effect because "camera" is already an element of the tags array:以下$addToSet操作无效,因为"camera"已经是tags数组的元素:

db.inventory.updateOne(
   { _id: 1 },
   { $addToSet: { tags: "camera"  } }
)

$each Modifier修饰符

You can use the $addToSet operator with the $each modifier. 您可以将$addToSet运算符与$addToSet修饰符一起使用。The $each modifier allows the $addToSet operator to add multiple values to the array field.$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.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" ]
}
←  $[<identifier>]$pop →