Skip to main content

What is the difference between $push and $addToSet?

Junior MongoDB
Quick Answer $push appends a value to an array even if it already exists - can create duplicates. $addToSet adds a value only if it doesn't already exist in the array - like a set in math. Use $addToSet when maintaining unique values (tags, categories, user IDs). Use $push when order matters or duplicates are allowed (event log entries).

Answer

$push adds an element to an array even if it already exists. $addToSet adds it only if it is not present, preventing duplicates.
S
SugharaIQ Editorial Team Verified Answer

This answer has been peer-reviewed by industry experts holding senior engineering roles to ensure technical accuracy and relevance for modern interview standards.

Want to bookmark, take notes, or join discussions?

Sign in to access all features and personalize your learning experience.

Sign In Create Account

Source: SugharaIQ

Ready to level up? Start Practice