KoderSolution Logo
HomeArticlesTutorialsForumAI LabRun Code
KoderSolution Logo

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

Engineering Newsletter

Join 100,000+ engineers receiving curated high-signal content weekly.

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.js

Topic Hub & Articles

Node.js Intro

10 min

Recap Quiz

5 Questions

Node.js Get Started

10 min

Node.js Modules

10 min

Node.js HTTP Module

10 min

Recap Quiz

5 Questions

Node.js File System

10 min

Node.js URL Module

10 min

Node.js NPM

10 min

Recap Quiz

5 Questions

Node.js Events

10 min

Node.js Upload Files

10 min

Node.js Email

10 min

Recap Quiz

5 Questions

Node.js Buffer

10 min

Node.js Streams

10 min

Node.js Crypto

10 min

Recap Quiz

5 Questions

Node.js OS Module

10 min

Node.js Path Module

10 min

Node.js Global Objects

10 min

Recap Quiz

5 Questions

Node.js Process

10 min

Node.js Child Processes

10 min

Node.js Worker Threads

10 min

Recap Quiz

5 Questions

Node.js DNS Module

10 min

Node.js Query String

10 min

MySQL Connect

10 min

Recap Quiz

5 Questions

MySQL Create Database

10 min

MySQL Order By

10 min

Recap Quiz

5 Questions

MongoDB Intro

10 min

Recap Quiz

5 Questions

MongoDB Create Database

10 min

MongoDB Create Collection

10 min

MongoDB Insert

10 min

Recap Quiz

5 Questions

MongoDB Find

10 min

MongoDB Query

10 min

MongoDB Sort

10 min

Recap Quiz

5 Questions

MongoDB Delete

10 min

MongoDB Update

10 min

MongoDB Limit

10 min

MongoDB Join

10 min

Progress
0%

0 / 35 Lessons

Node.jsNode.js MongoDB
Lesson

MongoDB Update

10 min reading
Free Course

MongoDB Update: Updating Documents with $set, $inc & $push Operators

Updating documents in MongoDB collections from Node.js applications is executed using updateOne() or updateMany(), combined with update operators like $set, $inc, $unset, and $push.

MongoDB Update Operators Pipeline

flowchart TD
    A["Update Document Payload"] --> B["$set: Set or replace field values"]
    A --> C["$inc: Increment numeric field values"]
    A --> D["$push: Append element to array field"]
    A --> E["$unset: Remove field from document"]

Practical Code Example

import { MongoClient, ObjectId } from 'mongodb';

const uri = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(uri);

async function executeDocumentUpdates() {
    try {
        await client.connect();
        const db = client.db('kodersolution_no_sql');
        const products = db.collection('products');

        // 1. updateOne with $set and $inc
        const filter = { title: 'Ergonomic Mouse' };
        const updateDoc = {
            $set: { inStock: true, lastUpdated: new Date() },
            $inc: { viewsCount: 1 } // Increment numeric view counter by 1
        };

        const updateOneResult = await products.updateOne(filter, updateDoc);
        console.log(`Matched: ${updateOneResult.matchedCount} | Modified: ${updateOneResult.modifiedCount}`);

        // 2. updateOne with Upsert option ({ upsert: true })
        const upsertFilter = { sku: 'KEYBOARD-MECH-01' };
        const upsertPayload = {
            $set: { title: 'RGB Mechanical Keyboard', price: 149.99, sku: 'KEYBOARD-MECH-01' }
        };

        const upsertResult = await products.updateOne(upsertFilter, upsertPayload, { upsert: true });
        console.log(`Upsert Result - Inserted ID: ${upsertResult.upsertedId || 'Existing Updated'}`);
    } catch (err) {
        console.error('MongoDB Update Error:', err.message);
    } finally {
        await client.close();
    }
}

executeDocumentUpdates();

Best Practices & Gotchas

  • Always Use Atomic Update Operators: Always wrap fields inside update operators like $set or $inc; passing a plain object { price: 100 } replaces the entire document.
  • Use { upsert: true }: Set { upsert: true } if you want MongoDB to create a new document automatically if no documents match the search filter.
  • Inspect matchedCount vs modifiedCount: matchedCount reports documents matching the filter; modifiedCount reports documents whose data was altered.

Self-Check Challenge

What happens to an existing document if you pass { price: 99 } without an operator like $set to updateOne()?

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

Recommended Courses & Books

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum