Stage 2 · Lesson 7 of 9
Upserts
An updates the matching document, or inserts a new one if none matches. Pass { upsert: true } to updateOne. The new document is built from the filter's equality plus the update, and $setOnInsert sets fields only when a document is created, such as a createdAt time.
Upserts suit counters, sync jobs and "save my settings" features, where you do not care whether the document existed. findOneAndUpdate with upsert: true does the same and also returns the document. Two upserts arriving at the same moment can both find nothing and both insert, so put a on the fields in the filter; the database then rejects or retries the second one.
Common trapan upsert whose filter uses a range or $ne and inserts a document missing the field you meant to match.
A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock
Resources for this stage
Start with
- CourseFreeMongoDB University
MongoDB
Free: the CRUD lessons on inserting, finding, replacing, updating and deleting documents, with labs