0
0
MongoDBquery~10 mins

$addToSet accumulator for unique arrays in MongoDB - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - $addToSet accumulator for unique arrays
Start aggregation
Group documents
For each group
Check if value in array?
YesSkip adding
No
Add value to array
Return unique array per group
The $addToSet accumulator collects unique values into an array for each group during aggregation.
Execution Sample
MongoDB
db.sales.aggregate([
  { $group: {
      _id: "$item",
      uniqueStores: { $addToSet: "$store" }
  }}
])
Groups sales by item and collects unique store names into an array for each item.
Execution Table
StepDocument ProcessedCurrent Group (_id)Current uniqueStores ArrayAction Taken
1{item: 'apple', store: 'A'}apple[]Add 'A' to uniqueStores
2{item: 'apple', store: 'B'}apple['A']Add 'B' to uniqueStores
3{item: 'apple', store: 'A'}apple['A', 'B']Skip 'A' (already in uniqueStores)
4{item: 'banana', store: 'A'}banana[]Add 'A' to uniqueStores
5{item: 'banana', store: 'C'}banana['A']Add 'C' to uniqueStores
6{item: 'banana', store: 'C'}banana['A', 'C']Skip 'C' (already in uniqueStores)
7{item: 'apple', store: 'C'}apple['A', 'B']Add 'C' to uniqueStores
8No more documents-Final arrays per groupAggregation complete
💡 All documents processed; unique arrays built per group.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5After 6After 7Final
uniqueStores for 'apple'[]['A']['A', 'B']['A', 'B']['A', 'B']['A', 'B']['A', 'B']['A', 'B', 'C']['A', 'B', 'C']
uniqueStores for 'banana'[][][]['A']['A', 'C']['A', 'C']['A', 'C']['A', 'C']['A', 'C']
Key Moments - 2 Insights
Why does $addToSet skip adding a value that already exists in the array?
Because $addToSet ensures uniqueness by checking if the value is already present before adding, as shown in steps 3 and 6 where duplicates are skipped.
What happens if the group is empty when $addToSet starts?
The array starts empty ([]) and values are added only if they are not duplicates, as seen at step 1 for 'apple' and step 4 for 'banana'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the uniqueStores array for 'apple' after processing step 2?
A['A']
B['A', 'B']
C[]
D['B']
💡 Hint
Check the 'Current uniqueStores Array' column at step 2 for group 'apple'.
At which step does the uniqueStores array for 'banana' first include 'C'?
AStep 4
BStep 6
CStep 5
DStep 3
💡 Hint
Look at the 'Current uniqueStores Array' for 'banana' and see when 'C' is added.
If a new document {item: 'apple', store: 'B'} is processed after step 7, what happens?
A'B' is skipped because it is already in uniqueStores
BuniqueStores resets to empty
C'B' is added again to uniqueStores
DAn error occurs
💡 Hint
Refer to steps 3 and 6 where duplicates are skipped.
Concept Snapshot
$addToSet accumulator syntax:
{ $group: { _id: <groupKey>, uniqueArray: { $addToSet: <expression> } } }

Behavior:
- Collects unique values per group into an array
- Skips duplicates automatically

Key rule:
- Result arrays contain no repeated values
- Useful for gathering distinct elements in aggregation
Full Transcript
The $addToSet accumulator in MongoDB aggregation groups documents by a key and collects unique values into an array for each group. It processes each document, checks if the value is already in the array, and adds it only if it is not present. This ensures the resulting array contains unique elements. For example, grouping sales by item and collecting unique store names uses $addToSet to avoid duplicates. The execution table shows step-by-step how values are added or skipped. Beginners often wonder why duplicates are skipped or how the array starts empty; these are clarified by tracing the array state changes. This accumulator is essential for building distinct lists within aggregation pipelines.