MongoDB Update
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 === 0to assume a document was not found: If the submitted field already holds the exact same value,matchedCountis1whilemodifiedCountis0. CheckmatchedCountfor existence. - Using
$pushwithout$addToSetwhen duplicates are unwanted:$pushappends duplicate tags every time; use$addToSetwhen an array should behave like a unique set. - Mutating
req.bodystraight 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: '' } }).
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.
Test Your Knowledge
You've completed this section! Take a quick 5-question quiz to check your understanding.