Data changes constantly in applications. MongoDB provides powerful update mechanisms. You can update single records or perform bulk edits.
The updateOne() method modifies a single record. It finds the first document matching your filter. It applies the changes and ignores the rest.
The updateMany() method modifies all matches. It is used for bulk adjustments. For example, marking all older users as inactive.
You cannot just pass a raw object to update. You must use an update operator like $set. This tells MongoDB exactly how to alter the data.
The $set operator replaces a field's value. If the field doesn't exist, it creates it. This is the most common update command.
// Update the age of one specific user
db.users.updateOne(
{ name: "John Doe" },
{ $set: { age: 31 } }
);
// Mark all users with age 25 as verified
db.users.updateMany(
{ age: 25 },
{ $set: { verified: true } }
);
An Upsert is an update or an insert combined. If the document is not found, MongoDB creates it. You pass { upsert: true } as the third parameter.
Sometimes you want to rewrite the whole document. You use replaceOne() for this. It strips away the old fields entirely.
Standard updates return an acknowledgment status. If you need the updated document immediately, use findOneAndUpdate(). It modifies the data and returns the object in one step.
Updates require special $set operators. Use updateOne() for safety, updateMany() for bulk. Upserts save time by handling missing records gracefully.
Which feature will automatically insert a document if the update filter finds no matches?