Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 70 ยท CRUD: update and delete

Upserts, Replace and findAndModify

Insert-or-update in one call with upsert and $setOnInsert, swap whole documents with replaceOne, and update-and-return atomically with findOneAndUpdate.

So far an update has meant "change the documents that match, or do nothing if none do". Real programs often need something slightly different: "make sure this document exists and has these values", "throw away the old version and store a new one", or "change this document and tell me what it looked like". MongoDB has a tool for each of these: the upsert option, replaceOne, and the findOneAndUpdate family.

All three work on a single document, and a write to a single document is atomic in MongoDB: other clients see either the old document or the new one, never a half-finished mix. That property is what makes these tools safe for counters, job queues and "create if missing" logic.

MongoDB cannot run on this site because there is no server. The mongosh blocks are real commands shown read-only. The runnable examples use a small stand-in engine written in plain JavaScript that models the behavior being explained, over arrays of documents. It supports only the operators the examples need, and it generates ids like oid001 instead of real ObjectIds.

Three tools, three jobs

Upsert Update if found, insert if not.
Replace Swap the whole document.
Find and modify Change it and get a copy back.
1 / 2

Upsert: update or insert

An upsert is an update with { upsert: true }. If at least one document matches the filter, it is updated as usual. If none match, MongoDB inserts a new document instead. This is perfect for page-view counters, "last seen" records and idempotent imports.

JavaScript
db.pageStats.updateOne(
  { path: "/home" },
  {
    $inc: { views: 1 },
    $setOnInsert: { firstSeen: new Date() }
  },
  { upsert: true }
)

The first call finds nothing, so it inserts a document. The second call matches that document and only increments views. The result tells you which happened:

JavaScript
// first call
{ acknowledged: true, matchedCount: 0, modifiedCount: 0,
  upsertedCount: 1, upsertedId: ObjectId("...") }
// second call
{ acknowledged: true, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }

Here is how the new document is built when the upsert inserts:

  1. Start with the equality conditions from the filter (path: "/home"). Conditions that use operators such as $gt are not copied, because they do not name one exact value.
  2. Apply the update operators, including $inc and $set.
  3. Apply $setOnInsert, which runs only in this insert case.
  4. Add an _id if there still is none. If the filter has _id: 5, that value is used.

$setOnInsert is the right place for values that must be written once and never touched again, such as createdAt or an initial status. Putting createdAt in $set would reset it on every call.

JS Upsert and $setOnInsert

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Upserts and duplicates

An upsert is "find, then insert if missing". Two clients can both see "missing" at nearly the same moment, and both insert, leaving two documents. The cure is a unique index on the field you filter by. The second insert then fails with a duplicate key error (code 11000), and your application can simply retry the upsert, which now finds the winner's document.

JavaScript
db.pageStats.createIndex({ path: 1 }, { unique: true })

You will learn about indexes in How Indexes Work. For now, remember the rule: an upsert on a field that must be unique needs a unique index behind it.

replaceOne: swap the whole document

updateOne with $set changes some fields and leaves the rest. replaceOne does something blunter: it replaces the entire matched document with the one you pass, keeping only the _id. The replacement must be a plain document with no update operators, and it must not try to change _id.

JavaScript
db.users.replaceOne(
  { _id: 42 },
  { name: "Ada Lovelace", email: "[email protected]", plan: "pro" }
)

Any field that was in the old document and is missing from the replacement is gone. This is useful when you receive a complete, authoritative copy of a record, for example from another system. It is dangerous if you forgot a field. When you only mean to change one or two fields, use $set.

You can also give replaceOne the upsert: true option. If nothing matches, the replacement document is inserted.

JS replaceOne drops missing fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

findOneAndUpdate: change it and get it back

Sometimes you need the document itself after an update: the next ticket number, the job you just claimed, the user as it looked before you changed it. You could run updateOne and then findOne, but another client may change the document between those two calls. findOneAndUpdate does both in one atomic step.

JavaScript
db.jobs.findOneAndUpdate(
  { status: "queued" },
  { $set: { status: "running", startedAt: new Date() } },
  { sort: { priority: -1 }, returnDocument: "after" }
)

The options that matter most:

Option Meaning
sort Which matching document to use when several match (the filter may match many; only one is changed).
returnDocument "before" (the default) returns the document as it was; "after" returns the updated version.
upsert Insert a document when nothing matches. With "before" you get null when it inserted.
projection Limit the fields in the returned document.

If nothing matches and upsert is off, you get null back. The value you receive depends on the driver version: current drivers return the document directly, while older ones wrapped it in a result object. In mongosh, the older option returnNewDocument: true also asks for the updated version. Always check the documentation of the driver you use.

Two related methods share the same idea: findOneAndReplace swaps the document and returns one version, and findOneAndDelete removes a document and returns what it contained (see Deleting Documents). The older findAndModify command, which findOneAndUpdate is built on, still exists, but new code should use the named methods.

JS Claim a job atomically

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Why atomic updates matter

Imagine two requests that both add one to a counter. If each one reads the value, adds one in the application, and writes the result back, both can read 10 and both write 11. One increment is lost. A single $inc runs inside the database as one operation, so both increments count and the result is 12.

sequenceDiagram
    participant A as Client A
    participant B as Client B
    participant DB as Document (count = 10)
    A->>DB: read count
    B->>DB: read count
    A->>DB: write count = 11
    B->>DB: write count = 11
    Note over DB: One increment is lost

Read-modify-write in the application loses an update; $inc does not.

JS Lost update versus $inc

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The sequence generator in the last example is a classic: one small counters collection and a findOneAndUpdate with upsert: true, $inc and returnDocument: "after" hands out gap-free numbers even with many clients. In most designs the default ObjectId is better, but sometimes a human-readable number such as an invoice number is a requirement.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does $setOnInsert do in an update with upsert: true?

    $setOnInsert is ignored when a document matches. It is the right place for values such as createdAt that must be written once.
  2. 2. An upsert filter is { sku: "A1", qty: { $gt: 5 } } and nothing matches. Which fields does the inserted document start with?

    Equality conditions name an exact value and are copied into the new document. Operator conditions such as $gt are not.
  3. 3. You call replaceOne with a document that omits the email field. What happens to the stored email?

    replaceOne swaps the whole document. Use updateOne with $set to change only some fields.
  4. 4. Which option makes findOneAndUpdate return the document as it is after the change?

    By default you get the document before the update. returnDocument: "after" returns the updated version.
  5. 5. How do you stop two concurrent upserts from creating duplicates?

    Without a unique index two clients can both decide the document is missing. The index makes the second insert fail, and a retry then finds the first document.

Summary

  • upsert: true updates a matching document or inserts a new one built from the filter's equality fields plus the update.
  • $setOnInsert writes values only when the upsert inserts; back an upsert with a unique index to avoid duplicates.
  • replaceOne swaps the whole document (keeping _id); fields you omit are removed, and update operators are not allowed.
  • findOneAndUpdate changes one document and returns it atomically; sort picks the document and returnDocument picks before or after.
  • Single-document writes are atomic, so operators such as $inc avoid the lost updates of read-modify-write code.

Next, learn how to remove data safely in Deleting Documents.