← Back to MongoDB Course | Chapter 4: CRUD — Update | Lesson 7 of 7

Upsert

An upsert updates a matching document or inserts a new one if nothing matches.

In this page:

  1. Upsert
Syntax
javascript
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

bash
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
  1. Upserting without a unique index
  2. Expecting an upsert to always insert
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.