Upsert Option — MongoDB Technical Interview Questions & Answers
Insert a document if the update filter matches nothing.
Upsert Option
- Simple meaning: upsert: true on an update inserts a new document if nothing matched.
- How to use: db.students.updateOne({ roll: 12 }, { $set: { name: "Asha", marks: 72 } }, { upsert: true }).
- Try this: update a roll that does not exist — a new student appears.
- Common mistake: upsert with a filter that is too wide, creating junk docs. Or forgetting $setOnInsert for fields only on insert.
- Interview tip: “Update or insert. Third options argument.”
Technical Interview Tip: updateOne + upsert for “save this roll”.
Code Examples for Upsert Option
Upsert Option — working example
db.users.updateOne(
{ email: "ada@example.com" },
{ $set: { name: "Ada", role: "admin", city: "Pune" }, $setOnInsert: { createdAt: new Date() } },
{ upsert: true }
)Upsert Option — upsert:true inserts a document when the filter matches nothing.
How to Explain Upsert Option to an Interviewer
What is upsert?
If no document matches the filter, insert one