What is the difference between the UpdateOne()
and the findOneAndUpdate()
methods in Mongo DB?
I can’t seem o understand their differences. Would appreciate it if a demonstrative example using UpdateOne()
and findOneAndUpdate
could be used.
What is the difference between the UpdateOne()
and the findOneAndUpdate()
methods in Mongo DB?
I can’t seem o understand their differences. Would appreciate it if a demonstrative example using UpdateOne()
and findOneAndUpdate
could be used.
2
Answers
Insert a document in an otherwise empty collection using the
mongo-shell
to start:UpdateOne
This operation returns an
UpdateResult
.FindOneAndUpdate
This operation returns the document that was updated.
FindOneAndUpdate
is preferred when you have to update a document and fetch it at the same time.If you need to return the New Document instead of the original document, you can use one of these ways:
returnDocument: "before" –> returns the original document (default).
returnDocument: "after" –> returns the updated document.
Or
returnNewDocument: false –> returns the original document (default).
returnNewDocument: true –> returns the updated document.
Note: If both options are set (returnDocument and returnNewDocument), returnDocument takes precedence.