The $addToSet accumulator helps you collect unique values into an array without duplicates.
$addToSet accumulator for unique arrays in MongoDB
db.collection.aggregate([
{
$group: {
_id: <grouping_key>,
uniqueValues: { $addToSet: <expression> }
}
}
])$addToSet adds values to an array only if they are not already present.
The _id field defines how documents are grouped.
db.orders.aggregate([
{
$group: {
_id: "$customerId",
uniqueProducts: { $addToSet: "$productId" }
}
}
])db.posts.aggregate([
{
$group: {
_id: null,
uniqueTags: { $addToSet: "$tags" }
}
}
])db.posts.aggregate([
{
$unwind: "$tags"
},
{
$group: {
_id: null,
uniqueTags: { $addToSet: "$tags" }
}
}
])This example inserts sales data with customers and their purchased items (some repeated). Then it unwinds the items array to single items and groups by customer to collect unique items each customer bought.
db.sales.insertMany([
{ _id: 1, customer: "Alice", items: ["apple", "banana", "apple"] },
{ _id: 2, customer: "Bob", items: ["banana", "orange"] },
{ _id: 3, customer: "Alice", items: ["banana", "kiwi"] }
])
db.sales.aggregate([
{ $unwind: "$items" },
{ $group: {
_id: "$customer",
uniqueItems: { $addToSet: "$items" }
}
}
])Time complexity: Generally O(n) where n is number of documents processed.
Space complexity: Depends on number of unique values collected per group.
Common mistake: Using $addToSet on arrays without $unwind collects arrays as elements, not individual values.
Use $addToSet when you want unique values; use $push if duplicates are allowed.
$addToSet collects unique values into an array during aggregation.
Use $unwind before $addToSet to get unique elements from arrays.
Great for removing duplicates in grouped results.
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
