What's the difference between findOneAndUpdate and findOneAndReplace?

Arsen Davtyan picture Arsen Davtyan · Aug 25, 2016 · Viewed 7k times · Source

I've recently installed the Java MongoDB Driver 3.1.1 version and I'm wondering what's the difference between findOneAndUpdate and findOneAndReplace?

In what situation should i use each one?

Answer

Kevin picture Kevin · Aug 26, 2016

The findOneAndUpdate searches the document and updates just the entries in the given update document. The other entries in the found document will remain.

The findOneAndReplace searches the document, removes everything inside this document and sets the entries of the given replacement document.

For example: You have a document {"name":"James", "age":"21"}

If you use the findOneAndUpdate function with the update document {"age":"22"}, you will get the document {"name":"James", "age":"22"}

If you use the findOneAndReplace function with the replacement document {"age":"22"}, you will get the document {"age":"22"} (The name has been deleted)

See: findOneAndUpdate Documentation and findOneAndReplace Documentation