Replace one vs Update one

What is the major difference between Replace one vs Update one?

Hey @Saravanakumar_71695

Perhaps the docs can help

https://docs.mongodb.com/manual/reference/method/db.collection.updateOne/index.html

https://docs.mongodb.com/manual/reference/method/db.collection.replaceOne/index.html

3 Likes

Thank you for the help @natac13

Hi @natac13, Thanks for your contribution.

Hi @Saravanakumar_71695 ,

Let’s see the parameters of both of these functions.

updateOne({filter},{update},{other})
replaceOne({filter},{replacement},{other})

filter specifies the kind of documents that we want to match.

Now, in the case of updateOne(), when any document is returned we perform an update operation on it such as adding a filed, removing an existing field, updating the values of an existing field and many other types of update operations.

However, in the case of replaceOne(), when any document is returned we replace it entirely with a new document.

For more information, please refer our documentation on replaceOne() and updateOne()

Hope it helps. If you still have any query, please feel free to get back to us.

Happy Learning :slight_smile:

Thanks,
Shubham Rajan
Curriculum Support Engineer

1 Like

If I may add one more thing, replaceOne() is equivalent to:

updateOne(
   <fiter>,
   {
      $set: {},
      $addFields: {},
      $unset: {}
   }
)

But of course the physical order of the fields will differ between the two if you add/remove fields with updateOne() because new fields are added to the end of the document.

And the _id field remains immutable.