Bobcares

MongoDB findOneAndUpdate | Beginners Guide

by | Aug 15, 2023

The collection’s first document that satisfies the search criteria is updated via the findOneAndUpdate() in MongoDB. Bobcares, as a part of our Server Management Service offers solutions to every query that comes our way.

The findOneAndUpdate() in MongoDB

The findOneAndUpdate() method updates the first document in the collection that fits the selection criteria. If more than one document matches the selection criteria, just the first document will update. The _id field’s value does not change during this update.

If we want to return the updated document, we must then set the returnNewDocument parameter’s value to true. Otherwise, this function will return the old document. Three factors are required: the first is the selection criterion, the second is the new data that has to be updated, and the final two are not necessary.

This technique can also be used to replace embedded documents. This approach is also usable in transactions containing many documents. The syntax is as follows:

db.collection.findOneAndUpdate(

selection_criteria: <document>,

update_data: <document>, 

{

   projection: <document>,

    sort: <document>,

    maxTimeMS: <number>,

    upsert: <boolean>,

    returnNewDocument: <boolean>,

    collation: <document>,

    arrayFilters: [ <filterdocument1>, … ]

})

Parameters of findOneAndUpdate() in MongoDB

The selection criteria for the update is the first parameter. This parameter’s type is a document. A document that needs an update is the second parameter. This parameter’s type is also a document. And the third parameter is optional.

Other optional ones are the following: projection, sort, maxTimeMS, upsert, returnNewDocument, Collation, and arrayFilters.

If we wish to return the updated document, we must change the value of the returnNewDocument parameter to true. Otherwise, it returns the original document.

[Looking for a solution to another query? We’re happy to assist you.]

Conclusion

The article provides an outline of the findOneAndUpdate() method in MongoDB, along with an explanation of its parameters.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Never again lose customers to poor
server speed! Let us help you.