Question 8 / 50
ImportantMediumScenarioCRUD
A user hits 'save preferences' twice in a row. How would you write the update so the document is created if it does not exist, without inserting duplicates?
Think about it first.
Short answer
Use updateOne with upsert: true on a unique key — typically userId or email. The filter identifies the document; $set writes the fields; MongoDB inserts only if nothing matched.
Why?
Without a unique index on the filter field, two concurrent upserts can both miss and both insert. The unique index makes the second attempt conflict, which you retry as an update. upsert is the right tool for 'ensure this row exists'; it is the wrong tool for 'append an event' — that should be insertOne.
Example
db.preferences.updateOne(
{ userId: ObjectId("64a1b2c3d4e5f6a7b8c90001") },
{ $set: { theme: "dark" } },
{ upsert: true }
)Interview tip
Mention the unique index. Upsert without uniqueness is a duplicate-key race waiting to happen.
Common mistake
findOne then insertOne if missing. That is a classic race under concurrent requests.
How did you do?
Learn
Cheat Sheet