$push, $addToSet and $pull
Three operators cover most array writes, and the only one people confuse is $push versus $addToSet. Both append; only one checks whether the value is already there.
Given:
{
_id: 1,
skills: ["Node.js"]
}
Add
$push: {
skills: "MongoDB"
}
Result:
["Node.js", "MongoDB"]
Prevent duplicates
$addToSet: {
skills: "MongoDB"
}
If MongoDB already exists:
Nothing happens.
This distinction is important:
$push → always adds
$addToSet → adds only if not already present
Remove from array
$pull: {
skills: "MongoDB"
}
Try it
User 101 starts with ["Node.js", "Kafka"]:
db.users.updateOne(
{ _id: 101 },
{
$addToSet: { skills: "MongoDB" }
}
)
Run it twice: the second time modifiedCount is 0, because the value is already there. Swap $addToSet for $push and it gets added again.