MongoDB

Stage 2 · Lesson 7 of 9

Upserts

Reading and writing documents

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

  • CourseFree
    MongoDB University

    MongoDB

    Free: the CRUD lessons on inserting, finding, replacing, updating and deleting documents, with labs

Practise

  • Test filters and updates on your own sample documents and share the link when you get stuck

Keep handy

Mark this stage as not done?