Upsert
An upsert updates a matching document or inserts a new one if nothing matches.
In this page:
Syntax
db.collection_name.updateOne(
filter,
{ $set: { field: value } },
{ upsert: true }
)
Upsert
Add { upsert: true } to an update. If the filter matches nothing, MongoDB creates a document from the filter's equality fields plus the update. $setOnInsert sets fields only when a new document is created.
Upserts need a unique index to be fully safe under concurrency.
Note:
Use $setOnInsert for fields like createdAt that should never change.
Example: Upsert
test> db.visits.updateOne({ _id: "home" }, { $inc: { count: 1 } }, { upsert: true })
{
acknowledged: true,
matchedCount: 0,
modifiedCount: 0,
upsertedCount: 1,
upsertedId: 'home'
}
test> db.visits.updateOne({ _id: "home" }, { $inc: { count: 1 } }, { upsert: true })
{ acknowledged: true, matchedCount: 1, modifiedCount: 1 }
test> db.visits.find()
[ { _id: 'home', count: 2 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Upserting without a unique index
- Expecting an upsert to always insert
- Filters with operators producing unexpected fields
Chapter Summary
- upsert: true updates or inserts
- Filter equality fields seed the new document
- $setOnInsert sets on insert only
- Use a unique index for safety
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: