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.
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"]
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();
$set or $inc; passing a plain object { price: 100 } replaces the entire document.{ upsert: true }: Set { upsert: true } if you want MongoDB to create a new document automatically if no documents match the search filter.matchedCount vs modifiedCount: matchedCount reports documents matching the filter; modifiedCount reports documents whose data was altered.What happens to an existing document if you pass { price: 99 } without an operator like $set to updateOne()?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With