scroll
Home/Blog/Tutorial/Preserving MongoDB E…
Illustrative developer workspace with code on screen

Preserving MongoDB Engagement Counters During CMS Edits

Atomic $inc and targeted $set to avoid lost updates

11 min read
0 views

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 $set and $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 mongodb Node.js driver API and the MongoDB manual for $set and $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:

ts
1// ❌ Naive implementation – vulnerable to lost updates
2async function naiveUpdateArticle(
3  db: Db,
4  articleId: ObjectId,
5  payload: { title?: string; body?: string }
6) {
7  const coll = db.collection('articles');
8  // 1️⃣ Read the current document
9  const doc = await coll.findOne({ _id: articleId });
10  if (!doc) throw new Error('Article not found');
11
12  // 2️⃣ Mutate fields locally
13  const updates: any = { ...doc };
14  if (payload.title !== undefined) updates.title = payload.title;
15  if (payload.body !== undefined) updates.body = payload.body;
16  // NOTE: we *do not* touch views/likes here – they stay as read
17
18  // 3️⃣ Write the whole document back
19  await coll.replaceOne({ _id: articleId }, updates);
20}

If two editors run this function at nearly the same time:

  1. Both read the same views value (say, 10).
  2. Editor A increments views locally to 11 and writes the document.
  3. 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.

ts
1// ✅ Safe implementation using $set and $inc
2async function safeUpdateArticle(
3  db: Db,
4  articleId: ObjectId,
5  payload: { title?: string; body?: string }
6) {
7  const coll = db.collection('articles');
8
9  // Build the $set part only for fields we actually want to change
10  const setFields: Record<string, any> = {};
11  if (payload.title !== undefined) setFields.title = payload.title;
12  if (payload.body !== undefined) setFields.body = payload.body;
13
14  // The update document – $set for content, $inc for counters
15  const update: any = {};
16  if (Object.keys(setFields).length > 0) update.$set = setFields;
17  // Always include $inc – if you don’t want to change a counter, pass 0
18  update.$inc = { views: 0, likes: 0 }; // placeholders; adjust as needed
19
20  // Execute a single atomic update
21  const result = await coll.updateOne(
22    { _id: articleId },
23    update
24  );
25
26  if result.matchedCount === 0 {
27    throw new Error('Article not found');
28  }
29  return result;
30}

Why this works

  • $set only overwrites the fields you list; other fields (including views and likes) remain as they were on the server.
  • $inc increments 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 updateOne command, 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:

ts
1await coll.updateOne(
2  { _id: articleId },
3  { $inc: { views: 1 } }   // or { $inc: { likes: 1 } }
4);

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.

ts
1import { MongoClient, ObjectId } from 'mongodb';
2
3async function runConcurrencyTest() {
4  const uri = 'mongodb://localhost:27017';
5  const client = new MongoClient(uri);
6  await client.connect();
7  const db = client.db('cmsDemo');
8  const coll = db.collection('articles');
9
10  // Reset a test article
11  await coll.deleteMany({ _id: new ObjectId() });
12  const articleId = new ObjectId();
13  await coll.insertOne({
14    _id: articleId,
15    title: 'Original',
16    body: 'Body',
17    views: 0,
18    likes: 0,
19  });
20
21  // ----- Naive concurrent updates -----
22  async function naiveEditor(num: number) {
23    const doc = await coll.findOne({ _id: articleId });
24    if (!doc) return;
25    // Simulate a small edit
26    await new Promise(r => setTimeout(r, 10)); // tiny delay to increase race chance
27    await coll.replaceOne(
28      { _id: articleId },
29      {
30        ...doc,
31        title: `Edited by ${num}`,
32        // ❌ incorrectly trying to increment views locally
33        views: doc.views + 1,
34      }
35    );
36  }
37
38  await Promise.all([naiveEditor(1), naiveEditor(2)]);
39
40  const naiveResult = await coll.findOne({ _id: articleId });
41  console.log('After naive concurrent edits:', naiveResult);
42
43  // Reset counters for the safe test
44  await coll.updateOne(
45    { _id: articleId },
46    { $set: { views: 0, likes: 0 }, $set: { title: 'Original' } }
47  );
48
49  // ----- Safe concurrent updates -----
50  async function safeEditor(num: number) {
51    await coll.updateOne(
52      { _id: articleId },
53      {
54        $set: { title: `Edited by ${num}` },
55        $inc: { views: 1 }, // each editor wants to count their edit as a view
56      }
57    );
58  }
59
60  await Promise.all([safeEditor(1), safeEditor(2)]);
61
62  const safeResult = await coll.findOne({ _id: articleId });
63  console.log('After safe concurrent edits:', safeResult);
64
65  await client.close();
66}
67
68runConcurrencyTest().catch(console.error);

Expected outcome (illustrative)

  • After the naive test, views will likely be 1 instead of 2, and the title will reflect only the last editor’s write.
  • After the safe test, views will be 2 (each $inc applied) and the title will be whatever the last $set wrote (the second editor’s title, because $set overwrites, but the counters are correct).

Trade‑offs and Alternatives

ApproachProsConsWhen 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 transactionGuarantees 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 lockingDetects 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 collectionEliminates 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

  1. Unit test the update function
    Insert a known document, call safeUpdateArticle with a title change, then assert that $set changed only the title and that views/likes stayed the same.

  2. Run the concurrency test (as shown above) on a local MongoDB instance.
    Check that the final views equals the number of concurrent $inc operations.

  3. Explain the operation

    js
    1db.runCommand({
    2  explain: {
    3    update: "articles",
    4    updates: [
    5      {
    6        q: { _id: <articleId> },
    7        u: { $set: { title: "New" }, $inc: { views: 1 } },
    8        multi: false
    9      }
    10    ]
    11  }
    12})

    Look for "updatePlan": { "usingIndexScan": true } or similar to confirm the planner can use the _id index.

  4. 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 usually w: 1. Adjust if you need stronger guarantees.


Troubleshooting

SymptomLikely causeCheck / Fix
Counters not increasing after an editThe 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 editYou 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: WriteConcernFailedReplica 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 _idAccidentally 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 loadMany 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:

  1. Metadata update (editor‑driven) – only $set the SEO fields:

    ts
    1await coll.updateOne(
    2  { _id: articleId },
    3  { $set: { seo: { title: newTitle, description: newDesc } } }
    4);

    No $inc is touched, so the existing views field remains exactly as it was on the server.

  2. View‑count increment (background job or request handler) – only $inc the counter:

    ts
    1await coll.updateOne(
    2  { _id: articleId },
    3  { $inc: { views: 1 } }
    4);

    Because 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:

ts
{ $set: { seo: { … } }, $inc: { views: 1 } }

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!

Illustrative developer workspace with code on screen

#MongoDB#TypeScript#Concurrency#CMS#Database
Rakib Hasan Sohag

Rakib Hasan Sohag

MERN Stack / Full Stack Developer

Share: