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?
findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).
findOneAndUpdate() updates the first matching document in the collection that matches the filter . If no document matches the filter , no document is updated. The sort parameter can be used to influence which document is updated.
findOneAndReplace() Method. The findOneAndReplace() method replaces the first matched document based on the given selection criteria. By default, this method returns the original document. To return the replacement document, set the value of the returnNewDocument option to true.
By default, findOneAndUpdate() returns the document as it was before update was applied. You should set the new option to true to return the document after update was applied.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With