Q48: What is an 'upsert' operation in MongoDB?
An upsert (update or insert) is a conditional write option. If a document matching the query criteria exists, MongoDB updates it. If no matching document exists, MongoDB creates and inserts a new document combining query filter keys and update field values.
Key Takeaways
- Pass
{ upsert: true }in update queries. - Atomic operation preventing duplicate check-then-insert race conditions.
Knowledge Check
What happens when executing updateOne({ email: 'a@b.com' }, { $set: { name: 'A' } }, { upsert: true }) if no document matches?