$set and $unset — MongoDB Technical Interview Questions & Answers
Update operators for adding/updating or removing a field.
$set and $unset
- Simple meaning: $set changes or adds a field. $unset removes a field. Always in the update document, never as a find filter.
- How to use: db.students.updateOne({ roll: 12 }, { $set: { city: "Pune" } }). Remove: { $unset: { city: "" } }.
- Try this: add city, find, then $unset city.
- Common mistake: updateOne({ roll: 12 }, { city: "Pune" }) without $set — that can replace the whole document and wipe name/marks.
- Interview tip: “Always $set unless you intend to replace.”
Technical Interview Tip: updateOne + $set. Never a raw replacement by accident.
Code Examples for $set and $unset
$set and $unset — working example
db.users.updateOne(
{ email: "ada@example.com" },
{ $set: { role: "admin", lastSeen: new Date() }, $unset: { tempToken: "" } }
)$set and $unset — $set adds/updates fields; $unset removes fields — both can appear in one update.
How to Explain $set and $unset to an Interviewer
Why $set?
Updates fields without deleting the rest of the document