What if your database could keep your lists perfectly unique without you lifting a finger?
Why $addToSet accumulator for unique arrays in MongoDB? - Purpose & Use Cases
Imagine you have a list of friends' favorite movies written down on paper. Every time a friend tells you a new favorite, you write it down. But sometimes, you accidentally write the same movie twice because you forgot if it was already on the list.
Manually checking if a movie is already on the list before adding it is slow and easy to mess up. You might miss duplicates or spend too much time scanning the list, especially as it grows longer.
The $addToSet accumulator in MongoDB automatically adds items to an array only if they are not already present. This means it keeps your list unique without extra effort or mistakes.
if (!favoriteMovies.includes(movie)) { favoriteMovies.push(movie); }{$addToSet: {favoriteMovies: movie}}It lets you build clean, unique lists effortlessly inside your database queries, saving time and avoiding errors.
For example, when collecting tags users add to a blog post, $addToSet ensures each tag appears only once, no matter how many times users try to add it.
Automatically prevents duplicates: No need to manually check for existing items.
Saves time and reduces errors: Keeps your arrays clean and unique.
Works inside aggregation pipelines: Great for grouping and collecting unique values.
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
