OPTIONS
翻译或纠错本页面

$addToSet

Definition

$addToSet

The $addToSet operator adds a value to an array only if the value is not already in the array. If the value is in the array, $addToSet does not modify the array.

db.collection.update( <query>, { $addToSet: { <field>: <value> } } );

For example, if a collection inventory has the following document:

{ _id: 1, item: "filter", tags: [ "electronics", "camera" ] }

The following operation adds the element "accessories" to the tags array since "accessories" does not exist in the array:

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

However, the following operation has no effect as "camera" is already an element of the tags array:

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

Behavior

  • $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.

  • If the field is absent in the document to update, $addToSet adds the array field with the value as its element.

  • If the field is not an array, the operation will fail.

  • If the value is an array, $addToSet appends the whole array as a single element. To add each element of the value separately, use $addToSet with the $each modifier. See Modifiers for details.

  • 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 field and values and the fields are in the same order.

    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.

Modifiers

You can use the $addToSet operator with the $each modifier. The $each modifier allows to $addToSet operator to add multiple values to the array field.

A collection inventory has the following document:

{ _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:

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

The operation adds only "camera" and "accessories" to the tags array since "electronics" already exists in the array:

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

参见

$push

←   $ (update) $pop  →