Update Documents

Update Documents in MongoDB

Data changes constantly in applications. MongoDB provides powerful update mechanisms. You can update single records or perform bulk edits.

Updating One Document

The updateOne() method modifies a single record. It finds the first document matching your filter. It applies the changes and ignores the rest.

Updating Multiple Documents

The updateMany() method modifies all matches. It is used for bulk adjustments. For example, marking all older users as inactive.

Update Operators

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

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 Examples:

// 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 } } );

Upserts

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.

Replacing Documents

Sometimes you want to rewrite the whole document. You use replaceOne() for this. It strips away the old fields entirely.

Returning Updated Data

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.

Summary

Updates require special $set operators. Use updateOne() for safety, updateMany() for bulk. Upserts save time by handling missing records gracefully.

Exercise

Which feature will automatically insert a document if the update filter finds no matches?