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.