You already know how to update documents by adding, removing, renaming fields, or changing field values. But what if you simply want to replace the entire document? This is where the replaceOne method comes in handy. It replaces the entire document without requiring any update operators.
Here’s the syntax for replaceOne:
The filter parameter specifies the criteria for selecting the document to be replaced. The replacement parameter is the new document that will replace the existing one. The optional options parameter allows you to pass additional options, including the upsert flag, which we'll cover shortly.
Let’s replace an old document with a new one in the comic_book_store_db dataset. Suppose we have new comprehensive data about the first issue of "Deadpool" and want to replace the old document with this new information.
In this code, the replaceOne method searches for the document with title: "Deadpool" and issue_number: 1. If it finds the document, it replaces it with the new document provided. The old document is entirely replaced by the new one, with all the specified fields. However, the _id field remains unchanged as it uniquely identifies the document in the collection.
The upsert option combines the actions of updating and inserting. It works with updateOne, updateMany, and replaceOne. If a document matching the filter criteria does not exist, the upsert option will insert a new document based on the criteria and update information provided.
The syntax looks like this:
