🗄️ Node.js – MongoDB: CRUD Operations
Estimated reading: 3 minutes 274 views

Node.js – MongoDB Update – Modify Documents in MongoDB with Node.js


Introduction – Why Use Update in MongoDB with Node.js?

In any real-world app, data changes over time. Whether you need to update a user profile, change order status, or modify inventory values, MongoDB’s updateOne() and updateMany() methods allow you to modify documents directly from your Node.js backend.

In this guide, you’ll learn:

  • Use updateOne() and updateMany() to modify data
  • Use update operators like $set, $inc, and $unset
  • Match specific documents using filter conditions
  • Handle responses and affected document counts

Setup – MongoDB Connection File (db.js)

const { MongoClient } = require('mongodb');

const url = 'mongodb://127.0.0.1:27017';
const client = new MongoClient(url);
const dbName = 'appDB';

async function getDB() {
  await client.connect();
  console.log(' Connected to MongoDB');
  return client.db(dbName);
}

module.exports = getDB;

Update a Single Document – updateOne()

const getDB = require('./db');

async function updateUser() {
  const db = await getDB();
  const result = await db.collection('users').updateOne(
    { name: 'Alice' }, // filter
    { $set: { email: 'alice2025@example.com' } } // update
  );

  console.log(' Matched:', result.matchedCount);
  console.log(' Modified:', result.modifiedCount);
}

updateUser();

Output:

 Matched: 1  
 Modified: 1

$set updates only the specified fields.


Update Multiple Documents – updateMany()

const result = await db.collection('users').updateMany(
  { role: 'guest' },
  { $set: { status: 'inactive' } }
);
console.log(' Updated users:', result.modifiedCount);

Great for bulk updates based on roles, categories, tags, etc.


Increase a Value – $inc Operator

await db.collection('users').updateOne(
  { name: 'Bob' },
  { $inc: { loginCount: 1 } }
);

Increments loginCount by 1.


Remove a Field – $unset Operator

await db.collection('users').updateOne(
  { name: 'Charlie' },
  { $unset: { temporaryFlag: "" } }
);

Deletes the temporaryFlag field from the document.


Upsert – Insert If Not Exists

await db.collection('users').updateOne(
  { name: 'Diana' },
  { $set: { age: 32 } },
  { upsert: true }
);

If Diana doesn’t exist, MongoDB will create the document.


Best Practices for Updating MongoDB in Node.js

Practice Why It’s Important
Always use filtersPrevents unintended updates
Use $set, $inc, $unsetKeeps updates safe and explicit
Check matchedCount and modifiedCountConfirms whether data was actually updated
Avoid overwriting full documentsReduces data loss risk
Use upsert for sync operationsEnsures data presence when needed

Summary – Recap & Next Steps

Updating data in MongoDB with Node.js is efficient and flexible. From single-field tweaks to full record updates, MongoDB’s syntax is expressive and developer-friendly.

Key Takeaways:

  • Use updateOne() for a single match, updateMany() for bulk
  • $set updates fields, $inc increments, $unset deletes fields
  • Use upsert to insert if the document doesn’t exist
  • Always check match/modify counts to verify success

Real-world relevance:
Used in profile updates, admin controls, inventory management, subscription renewals, and background jobs.


FAQs – Updating Documents in MongoDB with Node.js


What’s the difference between updateOne and replaceOne?
updateOne() updates only specified fields; replaceOne() replaces the entire document.


How do I update a nested field in MongoDB?
Use dot notation:

{ $set: { "address.city": "Mumbai" } }

Can I update and insert if not found?
Yes, with { upsert: true } option.


How do I remove a field from all documents?
Use updateMany() with $unset:

{ $unset: { fieldName: "" } }

Can I use dynamic values in updates?
Yes. Just pass JavaScript variables inside the $set or $inc object.


Share Now :
Share

♻️ Node.js – MongoDB Update

Or Copy Link

CONTENTS
Scroll to Top