Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use cases for updateOne over findOneAndUpdate in MongoDB [duplicate]

I think that findOneAndUpdate carries out an atomic operation, so I'm assuming that updateOne does not.

Why would you choose updateOne over findOneAndUpdate and avoid an atomic operation and have to spend extra time checking if the updates were atomic?

I would appreciate some insight or a use case.

like image 349
Nick Pineda Avatar asked Mar 24 '16 20:03

Nick Pineda


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

Does findOneAndUpdate create new?

When true , findOneAndUpdate() either: Creates a new document if no documents match the filter . For more details see upsert behavior.

Is findOneAndUpdate atomic MongoDB?

With the exception of an unindexed upsert, findOneAndUpdate() is atomic. That means you can assume the document doesn't change between when MongoDB finds the document and when it updates the document, unless you're doing an upsert.

What does findOneAndUpdate return?

The findOneAndUpdate() function is used to find a matching document and update it according to the update arg, passing any options, and returns the found document (if any) to the callback.


1 Answers

I think that findOneAndUpdate carries out an atomic operation, so I'm assuming that updateOne does not.

Why are you assuming that?

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

I think that's the main difference. So the use case of updateOne is when you don't need the document and want to save a bit of time and bandwidth.

like image 117
Ilya Avatar answered Oct 02 '22 17:10

Ilya