0
0
MongoDBquery~5 mins

$addToSet accumulator for unique arrays in MongoDB

Choose your learning style9 modes available
Introduction

The $addToSet accumulator helps you collect unique values into an array without duplicates.

When you want to gather all unique tags used in blog posts.
When you need a list of unique product categories from sales data.
When collecting unique user IDs who liked a post.
When summarizing unique cities customers come from.
When you want to avoid duplicate entries in an array during aggregation.
Syntax
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.

Examples
Groups orders by customer and collects unique product IDs each customer bought.
MongoDB
db.orders.aggregate([
  {
    $group: {
      _id: "$customerId",
      uniqueProducts: { $addToSet: "$productId" }
    }
  }
])
Collects unique arrays of tags from all posts (note: if tags is an array, this collects arrays, not individual tags).
MongoDB
db.posts.aggregate([
  {
    $group: {
      _id: null,
      uniqueTags: { $addToSet: "$tags" }
    }
  }
])
Unwinds tags array to get individual tags, then collects unique tags across all posts.
MongoDB
db.posts.aggregate([
  {
    $unwind: "$tags"
  },
  {
    $group: {
      _id: null,
      uniqueTags: { $addToSet: "$tags" }
    }
  }
])
Sample Program

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.

MongoDB
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" }
    }
  }
])
OutputSuccess
Important Notes

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.

Summary

$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.