Updating Documents
updateOne, updateMany, upsert, and update operators
Skills taught: mongodb.crud-update
Update Methods
MongoDB provides four update methods: updateOne() modifies the first matching document, updateMany() modifies all matches, replaceOne() replaces the entire document (keeping the _id), and findOneAndUpdate() returns the document before or after updating it.
Common Update Operators
const products = db.collection('products');
// $set — set one or more field values
await products.updateOne(
{ name: 'Wireless Headphones' }, // filter
{ $set: { price: 2199, inStock: true, updatedAt: new Date() } }
);
// $unset — remove a field
await products.updateOne(
{ name: 'USB-C Hub' },
{ $unset: { oldField: '' } } // value doesn't matter
);
// $inc — increment (or decrement) a numeric field atomically
await products.updateOne(
{ _id: productId },
{ $inc: { views: 1, stock: -1 } } // increment views, decrement stock
);
// $mul — multiply a numeric field
await products.updateMany(
{ category: 'Electronics' },
{ $mul: { price: 0.9 } } // apply 10% discount to all electronics
);
// $min / $max — only update if new value is less/greater than current
await products.updateOne(
{ _id: productId },
{ $max: { highestPrice: 2999 } } // only sets if 2999 > current highestPrice
);
Array Update Operators
// $push — add element to array
await users.updateOne(
{ email: 'alice@example.com' },
{ $push: { tags: 'premium' } }
);
// $addToSet — add to array only if not already present (like a set)
await users.updateOne(
{ email: 'alice@example.com' },
{ $addToSet: { roles: 'editor' } } // won't add duplicates
);
// $pull — remove all elements matching a condition
await users.updateOne(
{ email: 'alice@example.com' },
{ $pull: { tags: 'trial' } } // remove 'trial' from tags array
);
// $pop — remove first (-1) or last (1) element
await users.updateOne(
{ email: 'alice@example.com' },
{ $pop: { recentActivity: 1 } } // remove last activity log entry
);
// $push with $each — add multiple elements at once
await users.updateOne(
{ email: 'alice@example.com' },
{ $push: { tags: { $each: ['vip', 'newsletter'], $slice: -10 } } }
// $slice keeps only last 10 tags (auto-trims the array)
);
Tip: Use $addToSet instead of $push when you want array elements to remain unique. $push always appends, even if the value already exists.
Upsert — Create or Update
An upsert (update + insert) inserts the document if no match is found, or updates it if a match exists. Set { upsert: true } as the third argument.
// Upsert: creates a pageView record if it doesn't exist,
// or increments the counter if it does
const result = await pageViews.updateOne(
{ url: '/home', date: todayString }, // filter
{ $inc: { views: 1 }, $setOnInsert: { createdAt: new Date() } },
{ upsert: true } // create if not found
);
if (result.upsertedCount > 0) {
console.log('Created new record:', result.upsertedId);
} else {
console.log('Updated existing record');
}
// $setOnInsert only sets fields when a new document is inserted (not on update)
await users.updateOne(
{ email: 'newuser@example.com' },
{
$set: { lastSeen: new Date() }, // always update lastSeen
$setOnInsert: { createdAt: new Date(), role: 'user' } // only on insert
},
{ upsert: true }
);
findOneAndUpdate — Atomic Read-Modify
// Get the document AFTER the update (returnDocument: 'after')
const updated = await products.findOneAndUpdate(
{ _id: productId },
{ $inc: { stock: -1 } },
{ returnDocument: 'after' } // 'before' returns the original
);
console.log('New stock level:', updated.stock);
// Use case: claim a task from a queue atomically
// No race condition — the update is atomic
const task = await tasks.findOneAndUpdate(
{ status: 'pending' },
{ $set: { status: 'processing', worker: workerId, startedAt: new Date() } },
{ sort: { priority: -1 }, returnDocument: 'after' } // process highest priority first
);
Warning: Using updateOne() without an operator (e.g., updateOne(filter, { name: 'Alice' })) will REPLACE the entire document, losing all other fields. Always use operators like $set inside the update document.
Frequently Asked Questions
How do I update all documents in a collection?
Use updateMany({}, { $set: { field: value } }) — the empty filter {} matches all documents. Be careful — this modifies every document in the collection.
What is the difference between updateOne() and replaceOne()?
updateOne() with operators ($set, $inc, etc.) modifies specific fields. replaceOne() replaces the ENTIRE document body (but preserves the _id). Use replaceOne() only when you intentionally want to swap out the whole document.
How do I return the updated document after an update?
Use findOneAndUpdate() with the option { returnDocument: 'after' }. This atomically updates the document and returns its new state. With returnDocument: 'before', you get the state before the update.