Replace Documents in MongoDB Collections using replaceOne

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet

Replace documents in MongoDB collections using replaceOne to completely overwrite existing documents with new data based on specified queries.

[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.