Concept Flow - $addToSet for unique array additions
Start Update
Check if value exists in array?
Skip add
Update document
Done
When updating a document, $addToSet checks if the value is already in the array. If not, it adds it uniquely.
db.users.updateOne(
{ _id: 1 },
{ $addToSet: { hobbies: "reading" } }
)| Step | Current hobbies array | Value to add | Exists in array? | Action | Resulting hobbies array |
|---|---|---|---|---|---|
| 1 | ["sports", "music"] | "reading" | No | Add "reading" | ["sports", "music", "reading"] |
| 2 | ["sports", "music", "reading"] | "reading" | Yes | Skip add | ["sports", "music", "reading"] |
| 3 | ["sports", "music", "reading"] | "music" | Yes | Skip add | ["sports", "music", "reading"] |
| 4 | ["sports", "music", "reading"] | "travel" | No | Add "travel" | ["sports", "music", "reading", "travel"] |
| 5 | ["sports", "music", "reading", "travel"] | "sports" | Yes | Skip add | ["sports", "music", "reading", "travel"] |
| 6 | ["sports", "music", "reading", "travel"] | "cooking" | No | Add "cooking" | ["sports", "music", "reading", "travel", "cooking"] |
| 7 | ["sports", "music", "reading", "travel", "cooking"] | "reading" | Yes | Skip add | ["sports", "music", "reading", "travel", "cooking"] |
| Exit | N/A | N/A | N/A | No more values to add | Final array unchanged |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | After 6 | Final |
|---|---|---|---|---|---|---|---|---|
| hobbies array | ["sports", "music"] | ["sports", "music", "reading"] | ["sports", "music", "reading"] | ["sports", "music", "reading"] | ["sports", "music", "reading", "travel"] | ["sports", "music", "reading", "travel"] | ["sports", "music", "reading", "travel", "cooking"] | ["sports", "music", "reading", "travel", "cooking"] |
$addToSet operator adds a value to an array only if it is not already present.
Syntax: { $addToSet: { field: value } }
Ensures array uniqueness without duplicates.
Can use $each to add multiple unique values.
If array field missing, it creates it with the value.
Useful for maintaining unique lists in documents.