How do you update documents in MongoDB?

Why Interviewers Ask This

Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid MongoDB basics — a prerequisite for any developer role.

Answer

MongoDB provides several update methods: updateOne(): updates the first document matching the filter. db.users.updateOne({ _id: id }, { $set: { name: "Alice Smith", updatedAt: new Date() } }). updateMany(): updates all matching documents. db.users.updateMany({ status: "inactive" }, { $set: { status: "archived" } }). replaceOne(): replaces the entire document (except _id). Update operators: $set: set field values (add if not exists); $unset: remove fields — { $unset: { tempField: "" } }; $inc: increment numeric field — { $inc: { views: 1, balance: -50 } }; $push: add element to array — { $push: { tags: "mongodb" } }; $pull: remove elements from array matching condition; $addToSet: add to array only if not already present; $pop: remove first (-1) or last (1) array element; $rename: rename a field; $mul: multiply a field's value; $min/$max: update only if new value is less/greater. Upsert: update if exists, insert if not: db.users.updateOne({ email: "new@example.com" }, { $set: { name: "New User" } }, { upsert: true }). findOneAndUpdate(): atomically finds and updates, returning the document before or after update.

Pro Tip

Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex MongoDB answers easy to follow.