MongoDB

Stage 2 · Lesson 8 of 9

Replacing versus updating

Reading and writing documents

replaceOne(filter, doc) swaps the whole document for a new one, keeping only _id. Any you leave out is gone. updateOne with operators such as $set changes only the fields you name.

In current and , updateOne refuses a plain document without operators, which protects you from replacing by accident. Replace fits when your code owns the entire document, such as saving a settings object it just loaded. Updating fits almost everything else, especially when several parts of an application write different fields of the same document.

findOneAndReplace and findOneAndUpdate also return the document, before or after the change, which saves a second read.

Common traploading a document, changing one field in code and replacing the whole thing, which silently undoes another request's change made in between.

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?