Bird
Raised Fist0
MongoDBquery~20 mins

$addToSet accumulator for unique arrays in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
MongoDB $addToSet Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
What is the output of this aggregation using $addToSet?
Consider a collection orders with documents:
{ "_id": 1, "items": ["apple", "banana"] }
{ "_id": 2, "items": ["banana", "orange"] }
{ "_id": 3, "items": ["apple", "orange"] }

What will be the result of this aggregation?
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: { _id: null, uniqueItems: { $addToSet: "$items" } } }
])
MongoDB
db.orders.aggregate([
  { $unwind: "$items" },
  { $group: { _id: null, uniqueItems: { $addToSet: "$items" } } }
])
A{"_id": null, "uniqueItems": ["apple", "banana", "orange"]}
B{"_id": null, "uniqueItems": ["apple", "banana"]}
C{"_id": null, "uniqueItems": ["banana", "orange"]}
D{"_id": null, "uniqueItems": ["apple", "orange"]}
Attempts:
2 left
💡 Hint
Think about how $unwind breaks arrays into single elements and $addToSet collects unique values.
🧠 Conceptual
intermediate
1:30remaining
What does $addToSet do in MongoDB aggregation?
Choose the best description of the $addToSet accumulator in MongoDB aggregation pipelines.
ACounts the number of documents in a group.
BAdds all values including duplicates to an array.
CAdds only unique values to an array, ignoring duplicates.
DCalculates the sum of numeric values.
Attempts:
2 left
💡 Hint
Think about how $addToSet handles duplicates.
📝 Syntax
advanced
2:30remaining
Which aggregation query correctly uses $addToSet to collect unique tags?
Given a collection posts with documents containing a tags array, which aggregation pipeline correctly collects all unique tags across all posts?
Adb.posts.aggregate([{ $unwind: "$tags" }, { $group: { _id: null, allTags: { $push: "$tags" } } }])
Bdb.posts.aggregate([{ $unwind: "$tags" }, { $group: { _id: null, allTags: { $addToSet: "$tags" } } }])
Cdb.posts.aggregate([{ $group: { _id: null, allTags: { $push: "$tags" } } }])
Ddb.posts.aggregate([{ $group: { _id: null, allTags: { $addToSet: "$tags" } } }])
Attempts:
2 left
💡 Hint
Remember $addToSet collects unique values, but if you add arrays directly, it won't flatten them.
❓ optimization
advanced
2:30remaining
How to optimize aggregation to collect unique values without $unwind?
You want to collect all unique tags from documents where each document has a tags array. Which approach is more efficient and correct?
AUse $unwind on tags, then $group with $addToSet on tags.
BUse $project to flatten tags, then $group with $push.
CUse $group with $addToSet directly on the tags array field.
DUse $group with $push on tags, then $unwind the result.
Attempts:
2 left
💡 Hint
Think about how $addToSet treats arrays versus individual elements.
🔧 Debug
expert
3:00remaining
Why does this aggregation return nested arrays instead of unique values?
Given this aggregation:
db.products.aggregate([
{ $group: { _id: "$category", uniqueTags: { $addToSet: "$tags" } } }
])

Each tags field is an array. The result shows uniqueTags as arrays inside an array, not a flat unique list.
What is the cause?
AMongoDB does not support $addToSet on arrays.
BThe _id field should be null to collect all tags.
CThe $group stage is missing a $unwind before grouping.
D$addToSet adds the entire tags array as one element, causing nested arrays.
Attempts:
2 left
💡 Hint
Think about what happens when you add arrays to a set.

Practice

(1/5)
1. What does the $addToSet accumulator do in a MongoDB aggregation pipeline?
easy
A. Counts the total number of documents in a group
B. Adds all values including duplicates into an array
C. Sorts the array elements in ascending order
D. Collects unique values into an array, avoiding duplicates

Solution

  1. Step 1: Understand $addToSet purpose

    $addToSet collects values but only keeps unique ones, no duplicates.
  2. Step 2: Compare with other accumulators

    Unlike $push which adds all values, $addToSet ensures uniqueness.
  3. Final Answer:

    Collects unique values into an array, avoiding duplicates -> Option D
  4. Quick Check:

    $addToSet = unique array [OK]
Hint: Remember: $addToSet means add unique only [OK]
Common Mistakes:
  • Confusing $addToSet with $push
  • Thinking it sorts the array
  • Assuming it counts documents
2. Which of the following is the correct syntax to use $addToSet in a MongoDB aggregation $group stage?
easy
A. { $group: { _id: "$category", uniqueItems: { $addToSet: "$item" } } }
B. { $group: { _id: "$category", uniqueItems: { $push: "$item" } } }
C. { $group: { _id: "$category", uniqueItems: { $addToSet: ["$item"] } } }
D. { $group: { _id: "$category", uniqueItems: { $addToSet: { $item } } } }

Solution

  1. Step 1: Identify correct $addToSet usage

    The correct syntax uses $addToSet with a field path as a string, like "$item".
  2. 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.
  3. Final Answer:

    { $group: { _id: "$category", uniqueItems: { $addToSet: "$item" } } } -> Option A
  4. Quick Check:

    Correct syntax = { $group: { _id: "$category", uniqueItems: { $addToSet: "$item" } } } [OK]
Hint: Use field path as string inside $addToSet [OK]
Common Mistakes:
  • Wrapping field in array inside $addToSet
  • Using $push instead of $addToSet
  • Using braces {} incorrectly around field
3. Given the collection documents:
{ "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" } } }]
medium
A. { "_id": "fruit", "uniqueItems": ["apple", "banana"] }
B. { "_id": "fruit", "uniqueItems": ["apple", "apple", "banana"] }
C. { "_id": "fruit", "uniqueItems": ["banana"] }
D. { "_id": "fruit", "uniqueItems": [] }

Solution

  1. Step 1: Group by category and collect unique items

    All documents have category "fruit". $addToSet collects unique "item" values.
  2. Step 2: Identify unique items

    Items are "apple", "banana", and another "apple" (duplicate). Unique set is ["apple", "banana"].
  3. Final Answer:

    { "_id": "fruit", "uniqueItems": ["apple", "banana"] } -> Option A
  4. Quick Check:

    Unique items = ["apple", "banana"] [OK]
Hint: Duplicates removed, only unique values remain [OK]
Common Mistakes:
  • Expecting duplicates in result array
  • Confusing $addToSet with $push
  • Ignoring grouping key
4. You wrote this aggregation but it throws an error:
[{ $group: { _id: "$category", uniqueItems: { $addToSet: item } } }]

What is the error and how to fix it?
medium
A. Wrong accumulator; use $push instead of $addToSet
B. Missing quotes around field path; fix by using "$item"
C. Missing $unwind stage before $group
D. Cannot use $addToSet inside $group

Solution

  1. Step 1: Identify syntax error in field reference

    Field paths must be strings with "$" prefix inside accumulators. Here, item is missing quotes and $.
  2. Step 2: Correct the syntax

    Change item to "$item" to fix the error.
  3. Final Answer:

    Missing quotes around field path; fix by using "$item" -> Option B
  4. Quick Check:

    Field path needs "$" and quotes [OK]
Hint: Always quote field paths with $ inside accumulators [OK]
Common Mistakes:
  • Forgetting $ before field name
  • Not quoting field path as string
  • Assuming $unwind is always required
5. You have documents with a field 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?
hard
A. [{ $project: { uniqueTags: { $addToSet: "$tags" } } }]
B. [{ $group: { _id: null, allTags: { $addToSet: "$tags" } } }]
C. [{ $unwind: "$tags" }, { $group: { _id: null, allTags: { $addToSet: "$tags" } } }]
D. [{ $unwind: "$tags" }, { $group: { _id: "$tags", count: { $sum: 1 } } }]

Solution

  1. Step 1: Use $unwind to flatten tags arrays

    $unwind breaks each array element into separate documents, allowing unique collection.
  2. Step 2: Group all tags into a unique set

    Grouping by null collects all tags into one array with $addToSet ensuring uniqueness.
  3. Final Answer:

    [{ $unwind: "$tags" }, { $group: { _id: null, allTags: { $addToSet: "$tags" } } }] -> Option C
  4. Quick Check:

    Unwind then addToSet = unique combined array [OK]
Hint: Unwind arrays before addToSet to get unique elements [OK]
Common Mistakes:
  • Trying to addToSet whole arrays without unwind
  • Using $project instead of $group for aggregation
  • Grouping by tags instead of null for combined result
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard