Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between findOneAndUpdate and findOneAndReplace?

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?

like image 983
Arsen Davtyan Avatar asked Aug 25 '16 19:08

Arsen Davtyan


People also ask

What is the difference between updateOne and findOneAndUpdate?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).

What is findOneAndUpdate in Mongodb?

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.

How do you use findOneAndReplace?

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.

What does findOneAndUpdate return?

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.


1 Answers

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

like image 90
Kevin Avatar answered Oct 05 '22 10:10

Kevin