$addToSet (Add to Set)

Last updated: 2026-10-09

$addToSet (Add to Set)

$addToSet adds a value to an array only if it is not already present, keeping the array free of duplicates. `{ $addToSet: { tags: 'mongodb' } }`. To add several values at once combine with $each. Duplicate detection compares whole values (nested documents field by field). Great for tags and follow lists.

CategoryUpdate Array
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $addToSet: { <array field>: <value> } }

⚙️ Parameters

array fieldThe array field to add to.
valueThe value to add; skipped if already present.

Returns:The update result

▶ Example

Run the commands below in your local mongosh (requires a running mongod):

// $addToSet: add tag (skipped if present)
db.articles.updateOne(
  { _id: 1 },
  { $addToSet: { tags: 'mongodb' } }
)

// Multiple values need $each
db.articles.updateOne(
  { _id: 1 },
  { $addToSet: { tags: { $each: ['database', 'nosql'] } } }
)

Output:

// Existing mongodb is not duplicated; database and nosql are appended

📌 Notes

📚 Related Tutorials

❓ FAQ

QWhat is the difference between $addToSet and $push?
A$addToSet dedups; $push appends and allows duplicates.
QHow do I add several values at once?
AUse $each: { $addToSet: { tags: { $each: ['a', 'b'] } } }.
QCan $addToSet add nested documents?
AYes; dedup compares the whole document.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏