Introduction
When a content management system (CMS) lets editors change an article’s title or body, the same document often stores engagement metrics such as views and likes. If the update routine reads the document, modifies the fields, and writes it back, two editors working at the same time can overwrite each other's increments – the classic lost‑update problem.
MongoDB provides atomic operators that let you change unrelated parts of a document in a single write operation: $set for fields you want to replace (e.g., the article payload) and $inc for counters that must only increase. By combining them you avoid read‑modify‑write cycles and guarantee that every increment is applied, regardless of concurrent edits.
This tutorial walks through:
- why a naïve approach loses updates,
- how to structure a TypeScript update that uses
$setand$inc, - a small concurrency test that demonstrates the safety of the atomic operation,
- trade‑offs and alternatives,
- verification steps,
- common troubleshooting points, and
- an answer to a concrete reader question.
Note: Verify the MongoDB driver version and server version you are using against the official documentation (e.g., the
mongodbNode.js driver API and the MongoDB manual for$setand$inc). Operator behavior is stable across recent versions, but write concern defaults and transaction support can differ.
The Lost‑Update Problem
What happens with a read‑modify‑write flow?
Imagine a CMS editor loads an article, changes the title, and then saves it. A simplified TypeScript function might look like this:
If two editors run this function at nearly the same time:
- Both read the same
viewsvalue (say, 10). - Editor A increments
viewslocally to 11 and writes the document. - Editor B, still holding the stale read (
views: 10), increments to 11 and overwrites A’s write.
The final views is 11 instead of the correct 12 – one increment vanished.
Visualising the race
Time → T0 T1 T2
Editor A: read(10) → inc → write(11)
Editor B: read(10) → inc → write(11)
Solution: Targeted $set + Atomic $inc
MongoDB’s update operators are applied server‑side and are atomic with respect to a single document. The operation below changes only the fields we specify, leaving everything else untouched.
Why this works
$setonly overwrites the fields you list; other fields (includingviewsandlikes) remain as they were on the server.$incincrements the counter in place on the server, so each call adds its amount regardless of what any client previously read.- The whole document is touched by a single
updateOnecommand, which MongoDB serialises per document.
Adjusting the counters in practice
When an editor merely saves a draft, you usually don’t want to touch views or likes. You can therefore call the function with $inc set to { views: 0, likes: 0 } (or omit the $inc entirely if you prefer a separate “increment counter” endpoint). When a user actually views or likes the article, a different endpoint issues:
Because each endpoint uses only $inc, there is no risk of overwriting content.
Concurrency Test
The following TypeScript snippet simulates two concurrent editors that each only change the article title while also (incorrectly) trying to increment a counter via a read‑modify‑write step. We then compare the outcome with the safe version.
This test is illustrative only; it has not been executed. Run it in a sandbox to observe the behavior.
Expected outcome (illustrative)
- After the naive test,
viewswill likely be 1 instead of 2, and the title will reflect only the last editor’s write. - After the safe test,
viewswill be 2 (each$incapplied) and the title will be whatever the last$setwrote (the second editor’s title, because$setoverwrites, but the counters are correct).
Trade‑offs and Alternatives
| Approach | Pros | Cons | When to consider |
|---|---|---|---|
Targeted $set + $inc (single updateOne) | Simple, no extra round‑trips, atomic per document, works with default write concern. | $set overwrites; if you need to merge arrays or objects you must use $push, $addToSet, etc. | Most CMS edit scenarios where content fields are independent of counters. |
| Multi‑document transaction | Guarantees atomicity across multiple collections (e.g., article + analytics). | Requires MongoDB 4.0+ replica set, adds overhead, more complex error handling. | When you must update the article and a separate analytics document in the same all‑or‑nothing step. |
| Version field / optimistic locking | Detects conflicts and lets you retry; useful if you need to reject stale edits rather than silently overwrite. | Adds a field, requires retry logic, still needs a read for the version unless you use findOneAndUpdate with $inc on the version. | High‑conflict environments where losing an edit is unacceptable and you want to inform the user. |
| Separate counters collection | Eliminates any chance of content updates affecting counters; you can shard counters independently. | Extra join‑like complexity (application‑level) and eventual consistency if not using transactions. | Very high write‑throughput on counters (e.g., millions of views/sec) where you want to isolate hot spots. |
For the typical CMS use case—occasional content edits and frequent but modest counter increments—the targeted $set + $inc approach is the sweet spot: minimal code, no extra infrastructure, and strong consistency guarantees per document.
Verification Steps
-
Unit test the update function
Insert a known document, callsafeUpdateArticlewith a title change, then assert that$setchanged only the title and thatviews/likesstayed the same. -
Run the concurrency test (as shown above) on a local MongoDB instance.
Check that the finalviewsequals the number of concurrent$incoperations. -
Explain the operation
jsLook for
"updatePlan": { "usingIndexScan": true }or similar to confirm the planner can use the_idindex. -
Monitor write concern
Ensure your driver’s write concern matches your durability requirements (e.g.,w: "majority"for replica sets). The examples use the driver’s default, which is usuallyw: 1. Adjust if you need stronger guarantees.
Troubleshooting
| Symptom | Likely cause | Check / Fix |
|---|---|---|
| Counters not increasing after an edit | The update omitted $inc or passed 0 unintentionally. | Verify the $inc object fields; log the update document before sending. |
| Title reverts to old value after a concurrent edit | You used replaceOne or update with a full document instead of $set. | Switch to $set for partial updates; avoid replaceOne unless you intend to overwrite the whole doc. |
MongoError: WriteConcernFailed | Replica set unavailable or write concern not satisfied. | Check replica set status (rs.status()) and consider lowering write concern for testing (w: 1). |
Duplicate key error on _id | Accidentally upserting with a non‑unique _id. | Ensure the filter targets the existing article; do not use upsert:true unless you intend to create a new doc. |
| Performance spikes under heavy edit load | Many large $set operations causing document growth and relocation. | Keep article size moderate; consider storing large blobs (e.g., markdown) in GridFS or a separate collection if they cause frequent document moves. |
Answering a Reader Question
Question:
“I’m building a blog where editors can change the article’s SEO metadata (title, description) while the page view count is updated in real time by a background job. How do I make sure the metadata updates don’t accidentally reset the view counter?”
Answer:
Use a separate update path for each concern:
-
Metadata update (editor‑driven) – only
$setthe SEO fields:tsNo
$incis touched, so the existingviewsfield remains exactly as it was on the server. -
View‑count increment (background job or request handler) – only
$incthe counter:tsBecause each command touches a disjoint set of fields, MongoDB applies them atomically and independently. Even if the two operations interleave, the final document will have both the latest SEO metadata and the correct accumulated view count.
If you ever need to change both in a single request (e.g., an editor saves and you also want to count that save as a view), combine them as shown earlier:
This guarantees that neither operation can overwrite the other’s effect.
Conclusion
By leveraging MongoDB’s atomic update operators—$set for mutable payload fields and $inc for counters—you eliminate the classic lost‑update scenario that plagues read‑modify‑write patterns. The approach is straightforward to implement in TypeScript, requires no extra infrastructure, and works reliably under concurrent edits.
Remember to:
- Keep your update objects minimal (only the fields you truly intend to change).
- Verify driver and server versions for any version‑specific behavior (e.g., default write concern).
- Test concurrency with a realistic load pattern before deploying to production.
With these patterns in place, your CMS can safely handle frequent content edits while preserving accurate engagement metrics. Happy coding!



