Upsert: insert or update
An upsert is “update, or insert if there was nothing to update”. It is one operation, so it does not have the race condition that a find-then-insert has - which is the reason to use it, not the convenience.
db.users.updateOne(
{
email: "denish@example.com"
},
{
$set: {
name: "Denish"
}
},
{
upsert: true
}
)
Meaning:
If document exists
→ update it
If it doesn't exist
→ insert it
Useful in:
- synchronization jobs
- migrations
- external integrations
- idempotent operations