- Reference >
- Operators >
- Update Operators >
- Array Update Operators >
- $addToSet
$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.The
$addToSet
operator has the form:To specify a
<field>
in an embedded document or in an array, use dot notation.
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.
Missing Field¶
If you use $addToSet
on a field that is absent in the document to
update, $addToSet
creates the array field with the specified
value as its element.
Field is Not an Array¶
If you use $addToSet
on a field that is not an array, the
operation will fail. For example, consider a document in a collection
foo
that contains a non-array field colors
.
The following $addToSet
operation on the non-array field
colors
fails:
Value to Add is An Array¶
If the value is an array, $addToSet
appends the whole array
as a single element.
Consider a document in a collection test
containing an array
field letters
:
The following operation appends the array [ "c", "d" ]
to the
letters
field:
The letters
array now includes the [ "c", "d" ]
array
as an element:
Tip
To add each element of the value separately, use the
$each
modifier with $addToSet
. See
$each Modifier for details.
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. 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.
Examples¶
Consider a collection inventory
with the following document:
Add to Array¶
The following operation adds the element "accessories"
to the
tags
array since "accessories"
does not exist in the array:
Value Already Exists¶
The following $addToSet
operation has no effect as
"camera"
is already an element of the tags
array:
$each
Modifier¶
You can use the $addToSet
operator with the
$each
modifier. The $each
modifier allows the
$addToSet
operator to add multiple values to the array
field.
A collection inventory
has the following document:
Then the following operation uses the $addToSet
operator
with the $each
modifier to add multiple elements to the
tags
array:
The operation adds only "camera"
and "accessories"
to the
tags
array since "electronics"
already exists in the array: