Replace Documents in MongoDB Collections using replaceOne

In this lesson, we learn that replacing a document in a MongoDB collection is done using the replaceOne method, which does not have a replaceMany equivalent.

We demonstrate how to search for a specific document, such as one with the name "Alice Smith," and replace it with a new document containing updated information like "John Doe."

This operation completely removes all existing fields from the original document and replaces them with those in the new document. After running the operation, we verify that only the new data remains in the collection.

Share with a coworker

Transcript

[00:00] In order to replace a document within a Mongo collection, we can use the replaceOne method. As we can see, there is no replaceMany equivalent, since that would be difficult to specify which exact document from a set is going to replace which in the replacement set, so there is just one. So the first object that we pass is going to be the query that would specify which exact document is going to be changed and here is the replacement. So let's first search for what is the first document that we've got in our collection. So this is Alice Smith, and we can see quite a lot of information over here.

[00:38] So let's get back to replace one. Now the document that we're going to change will be searched by Alice Smith query. And what we want to modify over here is going to be the name John Doe. After running the replace we can see that nothing has been inserted matched one, modified one And if we take a look at the first document over here, then we would see that all other properties are gone. And this is as expected, since this is a replacement, not an update operation.