$addToSet accumulator for unique arrays in MongoDB - Time & Space Complexity
When using the $addToSet accumulator in MongoDB, it is important to understand how the time it takes grows as the input data grows.
We want to know how the operation of adding unique items to an array scales with more data.
Analyze the time complexity of the following MongoDB aggregation snippet using $addToSet.
db.collection.aggregate([
{ $group: {
_id: "$category",
uniqueItems: { $addToSet: "$item" }
}}
])
This groups documents by category and collects unique items into an array for each group.
Look at what repeats as data grows:
- Primary operation: Checking if an item is already in the unique array before adding.
- How many times: For each document in a group, this check happens once.
As the number of documents in a group grows, the number of checks to keep items unique grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of operations grows roughly in direct proportion to the number of documents.
Time Complexity: O(n)
This means the time to build the unique array grows linearly with the number of documents processed.
[X] Wrong: "$addToSet adds items instantly without checking duplicates, so time stays constant."
[OK] Correct: The operation must check if each item is already in the set to keep it unique, so time grows as more items are processed.
Understanding how MongoDB handles uniqueness with $addToSet helps you explain data aggregation efficiency clearly and confidently.
"What if we replaced $addToSet with $push and then removed duplicates later? How would the time complexity change?"
Practice
$addToSet accumulator do in a MongoDB aggregation pipeline?Solution
Step 1: Understand
$addToSetpurpose$addToSetcollects values but only keeps unique ones, no duplicates.Step 2: Compare with other accumulators
Unlike$pushwhich adds all values,$addToSetensures uniqueness.Final Answer:
Collects unique values into an array, avoiding duplicates -> Option DQuick Check:
$addToSet= unique array [OK]
$addToSet means add unique only [OK]- Confusing
$addToSetwith$push - Thinking it sorts the array
- Assuming it counts documents
$addToSet in a MongoDB aggregation $group stage?Solution
Step 1: Identify correct
The correct syntax uses$addToSetusage$addToSetwith a field path as a string, like "$item".Step 2: Check other options for errors
{ $group: { _id: "$category", uniqueItems: { $push: "$item" } } } uses$push, not$addToSet. { $group: { _id: "$category", uniqueItems: { $addToSet: ["$item"] } } } wrongly wraps field in array. { $group: { _id: "$category", uniqueItems: { $addToSet: { $item } } } } uses braces incorrectly.Final Answer:
{ $group: { _id: "$category", uniqueItems: { $addToSet: "$item" } } } -> Option AQuick Check:
Correct syntax = { $group: { _id: "$category", uniqueItems: { $addToSet: "$item" } } } [OK]
$addToSet [OK]- Wrapping field in array inside
$addToSet - Using
$pushinstead of$addToSet - Using braces {} incorrectly around field
{ "category": "fruit", "item": "apple" }{ "category": "fruit", "item": "banana" }{ "category": "fruit", "item": "apple" }What will be the result of this aggregation?
[{ $group: { _id: "$category", uniqueItems: { $addToSet: "$item" } } }]Solution
Step 1: Group by category and collect unique items
All documents have category "fruit".$addToSetcollects unique "item" values.Step 2: Identify unique items
Items are "apple", "banana", and another "apple" (duplicate). Unique set is ["apple", "banana"].Final Answer:
{ "_id": "fruit", "uniqueItems": ["apple", "banana"] } -> Option AQuick Check:
Unique items = ["apple", "banana"] [OK]
- Expecting duplicates in result array
- Confusing
$addToSetwith$push - Ignoring grouping key
[{ $group: { _id: "$category", uniqueItems: { $addToSet: item } } }]What is the error and how to fix it?
Solution
Step 1: Identify syntax error in field reference
Field paths must be strings with "$" prefix inside accumulators. Here, item is missing quotes and $.Step 2: Correct the syntax
Changeitemto"$item"to fix the error.Final Answer:
Missing quotes around field path; fix by using "$item" -> Option BQuick Check:
Field path needs "$" and quotes [OK]
- Forgetting $ before field name
- Not quoting field path as string
- Assuming $unwind is always required
tags as arrays, some with duplicates:{ "_id": 1, "tags": ["red", "blue", "red"] }{ "_id": 2, "tags": ["blue", "green"] }Which aggregation pipeline will produce a single array of all unique tags across documents?
Solution
Step 1: Use
$unwindto flatten tags arrays$unwindbreaks each array element into separate documents, allowing unique collection.Step 2: Group all tags into a unique set
Grouping by null collects all tags into one array with$addToSetensuring uniqueness.Final Answer:
[{ $unwind: "$tags" }, { $group: { _id: null, allTags: { $addToSet: "$tags" } } }] -> Option CQuick Check:
Unwind then addToSet = unique combined array [OK]
- Trying to addToSet whole arrays without unwind
- Using $project instead of $group for aggregation
- Grouping by tags instead of null for combined result
Ready to prove it?
Pass the test and this pattern moves unknown
