$addToSet

noun

say it: “DOL-er ad-too-SET” /ˈdɑlər ˌæd tə ˈsɛt/

A MongoDB update operator that adds a value to an array only when the array doesn't already contain it.

What does $addToSet do in a MongoDB update?

$addToSet adds an item to an array field only when the array doesn't already hold that value, so the array never gets a duplicate. A second identical update changes nothing.

db.users.updateOne({ name: "Ana" }, { $addToSet: { favorites: 4 } });
db.users.updateOne({ name: "Ana" }, { $addToSet: { favorites: 4 } });
db.users.findOne({ name: "Ana" }).favorites;
// [ 4 ]

In a sentence

  • “$addToSet reports modifiedCount 0 when the value was already there.”
  • “Tapping the star twice still leaves one copy of the recipe in favorites, thanks to $addToSet.”

Level: Apprentice · More MongoDB terms at this level

Updated