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.