KoderSolutionKoderSolution LogoKoderSolution Logo
HomeArticlesTutorialsToolsRun CodeForumAI Lab
🟢

Node.js

Topic Hub & Articles

Node.js Intro

10 min

Node.js Get Started

10 min

Node.js Modules

10 min

Node.js HTTP Module

10 min

Node.js File System

10 min

Node.js URL Module

10 min

Node.js NPM

10 min

Node.js Events

10 min

Node.js Upload Files

10 min

Node.js Email

10 min

Node.js Buffer

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Streams

10 min

Node.js Crypto

10 min

Node.js OS Module

10 min

Node.js Path Module

10 min

Node.js Global Objects

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js Process

10 min

Node.js Child Processes

10 min

Node.js Worker Threads

10 min

Node.js DNS Module

10 min

Node.js Query String

10 min

Recap Quiz

Gated

Milestone Assessment

MySQL Connect

10 min

MySQL Create Database

10 min

Recap Quiz

Gated

Milestone Assessment

Node.js MySQL ORDER BY Clause

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Intro

10 min

MongoDB Create Database

10 min

MongoDB Create Collection

10 min

MongoDB Insert

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Find

10 min

MongoDB Query

10 min

MongoDB Sort

10 min

MongoDB Delete

10 min

MongoDB Update

10 min

Recap Quiz

Gated

Milestone Assessment

MongoDB Limit

10 min

MongoDB Join

10 min

Progress
0%

0 / 35 Lessons

KoderSolutionKoderSolution LogoKoderSolution Logo

The world’s most advanced technical ecosystem for modern software engineers. Learn, build, and grow with next-generation developer tools and resources.

Facebook PageX (Twitter) ProfileYouTube ChannelContact Support

Engineering Newsletter

Subscribe for weekly software engineering tutorials, architecture guides, and developer tool updates.

Platforms

  • Technical Articles
  • Interactive Tutorials
  • AI Coding Lab
  • Developer Forum
  • Developer Tools

Pages

  • About Us
  • Contact Us
  • Privacy Policy
  • Terms of Service
  • Refund Policy
  • Disclaimer
  • Advertisement

Popular Topics

  • PHP
  • Laravel
  • Python
  • React.Js
  • MySQL
© 2026 KoderSolutionAll Rights Reserved
Developed Bymaksudur.dev
Node.jsNode.js MongoDB
Lesson

MongoDB Update

10 min reading
Free Course

MongoDB Update in Node.js: Atomic Operators and Safe Modifications

Updating MongoDB documents in Node.js uses collection.updateOne(), collection.updateMany(), and collection.findOneAndUpdate() paired with atomic update operators like $set, $inc, and $push. Using update operators modifies only specific fields safely under concurrent requests without overwriting unrelated fields.

Atomic Updates with $set, $inc, and updatedAt

Always wrap changes inside an operator object ({ $set: { ... } }). Never pass a raw field object { name: 'New' } directly as the second argument—modern MongoDB drivers throw an error to stop accidental full-document replacement.

import { ObjectId } from 'mongodb';

async function updateProductStock(productsCollection, productId, soldQty, newTitle) {
  if (!ObjectId.isValid(productId)) {
    throw new Error('Invalid product ID');
  }

  const result = await productsCollection.updateOne(
    { _id: new ObjectId(productId), stock: { $gte: soldQty } },
    {
      $inc: { stock: -soldQty },
      $set: { title: newTitle, updatedAt: new Date() },
    }
  );

  return {
    matched: result.matchedCount,
    modified: result.modifiedCount,
  };
}

Notice how placing stock: { $gte: soldQty } inside the filter and $inc: { stock: -soldQty } inside the update makes inventory deduction atomic—preventing race conditions where two simultaneous buyers drive stock negative!

Returning the Updated Document with findOneAndUpdate()

When an API route needs the updated record right away, call collection.findOneAndUpdate(filter, update, { returnDocument: 'after' }). Remember to use returnDocument: 'after' in driver v4+ (replacing the older returnOriginal: false option).

Common Mistakes to Avoid

  • Checking modifiedCount === 0 to assume a document was not found: If the submitted field already holds the exact same value, matchedCount is 1 while modifiedCount is 0. Check matchedCount for existence.
  • Using $push without $addToSet when duplicates are unwanted: $push appends duplicate tags every time; use $addToSet when an array should behave like a unique set.
  • Mutating req.body straight into { $set: req.body }: Pick only allowed editable fields explicitly so callers cannot inject $set: { isAdmin: true }.

Frequently Asked Questions

What does { upsert: true } do in updateOne()?

If a document matches the filter, MongoDB updates it. If zero documents match, MongoDB inserts a new document combining the filter fields and update operators.

What is the difference between updateOne() and replaceOne()?

updateOne() applies atomic $set/$inc changes to targeted fields, whereas replaceOne() replaces the entire document body (keeping _id intact).

How do I remove an unwanted field from a document?

Use the $unset operator: updateOne({ _id }, { $unset: { legacyNotes: '' } }).

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol

Try it Yourself

Experiment with the code from this lesson in our interactive playground.

Open Playground
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

Related Developer Tools & Topic Hub

Node.js Topic Hub
JSON Formatter
Validate, format, and minify JSON
Regex Tester
Test regular expression patterns
JWT Decoder
Inspect JSON Web Token payloads
All Node.js Articles
Deep-dive guides, tips & discussions
PreviousMongoDB Delete
Continue JourneyTake Recap Quiz

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum