Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 70 ยท CRUD: update and delete

Updating Documents

Change MongoDB documents with updateOne and updateMany. Learn $set, $unset, $inc, $mul, $min, $max, $rename, $currentDate and matched versus modified counts.

Reading data is half the job. Applications also change it: a user edits a profile, a sale reduces stock, an order moves from "pending" to "shipped". In MongoDB you do this with update operators. Instead of sending back a whole new document, you send a small description of the change ("set this field, add 5 to that one") and the server applies it to every document your filter matches. That is cheaper to send, and it makes the change atomic for each document: other clients never see a half-applied update of one document.

This lesson covers updateOne, updateMany and the field and number operators. Arrays have their own operators in Updating Arrays, and creating-or-updating in one step comes in Upserts, Replace and findAndModify. Plain code blocks show real mongosh commands that cannot run here, since the site has no MongoDB server. The TryIts run on the site's practice engine: a JavaScript stand-in that applies update operators to an array of plain objects. The first part of each example is that engine; the lesson code starts after the line "end of engine". It follows MongoDB's rules for these operators, but it is not a database: it has no indexes, no concurrency and no atomic rollback, so a failing operator can leave a document half changed, which real MongoDB never does.

Update operators by job

Fields $set, $unset and $rename.
Numbers $inc, $mul, $min and $max.
Dates $currentDate stamps the server time.
Arrays $push, $pull and friends. See the next lesson.
1 / 2

updateOne, updateMany and the result

Both methods take a filter (the same filters you use in find), an update document made of operators, and optional settings:

JavaScript
db.staff.updateOne(
  { name: "Ana" },
  { $set: { title: "Senior Engineer" } }
)

db.staff.updateMany(
  { dept: "eng" },
  { $set: { team: "platform" } }
)

updateOne changes only the first document that matches, in no promised order, so use a filter that identifies exactly one document (usually _id). updateMany changes all matches. The update document must contain operators (keys starting with $). If you pass a plain document such as { title: "x" } to updateOne, MongoDB rejects it, because the update would be ambiguous; replacing a whole document is a separate method (replaceOne).

The result tells you what happened:

JavaScript
{ acknowledged: true, matchedCount: 2, modifiedCount: 1, upsertedCount: 0, upsertedId: null }

matchedCount is how many documents the filter found. modifiedCount is how many were actually changed. The two differ when an update would not change anything: setting a field to the value it already has, or $unset on a field that is not there, matches the document but does not modify it. A matchedCount of 0 means your filter found nothing, which is not an error. Always check the counts when an update matters.

Changing fields: $set, $unset and $rename

$set assigns a value, creating the field if it does not exist. It uses dot notation to reach inside embedded documents and creates the missing levels. $unset removes fields (the value you pass, usually "", is ignored). $rename changes a field's name and keeps its value.

JS $set, $unset and $rename with counts

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

No output.

Read the counts: the repeated $set reports matchedCount: 1, modifiedCount: 0; the $unset matches both engineers but modifies only Ben; $rename touches all three. Notice also that address.city created a whole address object for Ana and no one else, which is normal in a collection without a fixed schema, and a reason to check for missing fields in your queries (see Element and Evaluation Operators).

Several operators can appear in the same update, and the document is changed in one atomic step. You cannot, however, name the same field in two operators of one update (for example $set and $inc on salary): MongoDB reports a conflict.

Changing numbers: $inc, $mul, $min and $max

These four work on numeric fields and are the right tool whenever the new value depends on the old one:

  • $inc: { stock: -1 } adds a number (negative to subtract). A missing field starts from 0, so the field is created with the amount.
  • $mul: { price: 1.5 } multiplies. A missing field becomes 0, which surprises people.
  • $min: { lowest: 5 } sets the field only if 5 is smaller than the current value (or the field is missing).
  • $max: { highest: 5 } sets it only if 5 is larger.

Why not read the document, compute in your app and write it back? Because two clients doing that at the same time lose updates: both read stock 10, both write 9. $inc runs on the server inside the document write, so two concurrent decrements always end at 8. Atomicity and Single-Document Writes goes deeper. $currentDate sets a field to the server's current time ({ $currentDate: { updatedAt: true } }), which avoids depending on client clocks.

JS Numbers, dates and the $mul surprise

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

No output.

The $min sequence shows the logic: the first call creates lowestSeen (5), the second improves it to 3, and the third (9) matches the document but changes nothing, so modifiedCount stays 0. The failing $inc on a text field is a real MongoDB behavior too: the server refuses to add a number to a string and the whole update for that document fails.

Safe update habits

Updates are easy to get wrong in ways that quietly damage data. A few habits help:

  • Test the filter first. Run the same filter with find (or countDocuments) before running updateMany, especially an updateMany({}, ...), which touches every document.
  • Identify single documents by _id. updateOne with a loose filter changes whichever match the server meets first.
  • Check the counts. A matchedCount of 0 usually means a typo in the filter or a type mismatch (for example filtering on the number 5 when the stored value is the string "5").
  • Remember updateMany is not one transaction. Each document is updated atomically, but the set of documents is not: if it fails halfway, some are changed and some are not. For all-or-nothing changes across documents see Multi-Document Transactions.
  • Prefer operators over rewriting. $inc and $set on one field are safer and smaller than reading a document and saving all of it back.

Since MongoDB 4.2 the update can also be an aggregation pipeline (an array of stages), which lets a new value be computed from other fields of the same document. It is a real feature and cannot run here:

JavaScript
db.orders.updateMany({}, [{ $set: { total: { $add: ["$subtotal", "$shipping"] } } }])

Pipeline-style updates in depth

Classic operators such as $set and $inc can only write values you supply. They cannot say "set total to subtotal + shipping" or "set status to "vip" when spent is over 1,000 and "regular" otherwise", because the new value depends on the document's other fields. An update with an aggregation pipeline (MongoDB 4.2 and later) fixes that: you pass an array of stages instead of an update document, and every stage can use field paths and expressions.

JavaScript
db.orders.updateMany(
  { status: "paid" },
  [
    { $set: { total: { $add: ["$subtotal", "$shipping"] } } },
    { $set: { totalWithTax: { $round: [{ $multiply: ["$total", 1.2] }, 2] } } },
    { $unset: "legacyField" }
  ]
)

Only a few stages are allowed in an update pipeline, because the result must remain one document per matched document:

Stage Use
$set (alias $addFields) Add or overwrite fields with computed values
$unset (alias $project with exclusions) Remove fields
$replaceRoot / $replaceWith Replace the whole document with a computed one

What this makes possible

  • Computed fields from other fields: { $set: { fullName: { $concat: ["$first", " ", "$last"] } } }.
  • Per-document conditions with $cond or $switch, in a single round trip and atomically per document:
JavaScript
db.customers.updateMany({}, [
  { $set: {
      tier: { $switch: { branches: [
        { case: { $gte: ["$spent", 1000] }, then: "gold" },
        { case: { $gte: ["$spent", 250] },  then: "silver" }
      ], default: "bronze" } }
  } }
])
  • Several dependent fields at once, because each stage sees the result of the previous stage. In the first example, totalWithTax reads the total that the stage before it just wrote.
  • Swapping or copying fields safely: { $set: { a: "$b", b: "$a" } } swaps them, since both right-hand sides read the document as it was before the stage.
  • Changing types in place, a common migration: { $set: { price: { $toDouble: "$price" } } } (see the conversion operators in Expressions and Operators).
  • Updating array elements by rule with $map: { $set: { items: { $map: { input: "$items", as: "i", in: { $mergeObjects: ["$$i", { qty: { $max: ["$$i.qty", 1] } }] } } } } }. The positional operators cover simple cases; a pipeline handles complex ones.
  • Timestamps with the $$NOW variable: { $set: { updatedAt: "$$NOW" } }.

Gotchas

  1. Strings starting with $ are field paths. In a pipeline, { $set: { note: "$5 off" } } tries to read a field called 5 off. To store a literal dollar string, wrap it: { $set: { note: { $literal: "$5 off" } } }. A plain $set update document has no such trap.
  2. Operators are different. You cannot mix { $inc: ... } update operators into the array; write { $set: { n: { $add: ["$n", 1] } } } instead. Where classic operators work, they are shorter and read better.
  3. The pipeline form cannot use arrayFilters or positional $. Use $map and $filter.
  4. Missing fields behave like null in arithmetic. { $add: ["$a", 1] } gives null when a is missing, so guard with $ifNull: { $add: [{ $ifNull: ["$a", 0] }, 1] }.
  5. Upserts work ({ upsert: true }), and updateOne, updateMany and findOneAndUpdate all accept a pipeline. bulkWrite update operations do too.

As with every update, test the filter first, and run a pipeline update on a copy or a small $match before touching a whole collection.

The model below applies a pipeline of $set and $unset stages to documents, evaluating the expressions you saw. It is a stand-in written for this lesson and supports only a few operators.

JS An update pipeline with $set, $switch and $unset

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

No output.

Three things show up in the output. totalWithTax read the total written one stage earlier. Cy has no last name, so $concat produced null (a reminder to wrap such fields in $ifNull), and no shipping, so $ifNull supplied 0. And the $literal kept the text $5 off next order instead of treating it as a field path.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. An updateOne call returns matchedCount: 1 and modifiedCount: 0. What most likely happened?

    matchedCount counts documents the filter found. modifiedCount counts documents that really changed. A no-op update matches without modifying.
  2. 2. Why is { $inc: { stock: -1 } } better than reading the document and writing back stock - 1?

    Read-modify-write loses updates when two clients overlap. $inc is applied by the server inside the document write.
  3. 3. What does $mul: { rating: 3 } do when the document has no rating field?

    A missing field is treated as 0 for multiplication, so the new field holds 0. $inc, in contrast, creates the field with the given amount.
  4. 4. Which call changes every document where dept is 'eng'?

    updateMany applies the operators to all matches. updateOne stops after the first, and an update document without operators is rejected.

Summary

  • updateOne changes the first matching document; updateMany changes all matches; both take a filter and a document of update operators.
  • The result's matchedCount and modifiedCount differ when an update would not change anything.
  • $set assigns or creates fields (with dot notation for nested ones), $unset removes them, $rename renames them.
  • $inc, $mul, $min and $max change numbers on the server, which avoids lost updates. $mul on a missing field gives 0; $inc creates it.
  • $currentDate stamps the server time. Operators in one update are applied to a document atomically, but updateMany as a whole is not a transaction.
  • Test filters with find first, and use _id when you mean one document.

Next, learn to change the contents of arrays in Updating Arrays.