MongoDB

How to use findOneAndUpdate method in MongoDB

MongoDB supports multiple functions that are used to process data in databases. In any database, the data updating process is inevitable and is performed frequently. The findOneAndUpdate method is used to update a single document that matches the condition, and this method is an extension of the core update method of MongoDB.

The findOneAndUpdate() method returns the document after the update, whereas the updateOne() method of MongoDB also updates one document but it does not return any document.

In this article, you will learn to understand and apply the findOneAndUpdate() method of MongoDB to match and update a single document.

How findOneAndUpdate() works in MongoDB

The working mechanism of this method is based on the syntax given below:

db.collection-name.findOneAndUpdate({filter}, {update}, {options})

In the above syntax:

collection-name refers to the collection of a Mongo database in which the document resides.

{filter} is a condition to match the document.

{update} contains the field(s) and associated value(s) to be updated

{options} are the parameters to refine the update processing. For example, the “maxTimeMS” option is used to limit the time for execution of a query. If the specified time limit exceeds, the query will not be executed.

How to apply findOneAndUpdate() method in MongoDB

In this section, a detailed guide is provided with the help of several examples to use findOneAndUpdate() method:

Example 1: Updating a single document

For this example, we will use a “laptops” collection and the following content resides in it:

> db.laptops.find().pretty()

Text Description automatically generated

We want to add a “Status” field with the value “available” to the documents where the “Units” value is greater than or equal to “50“. The command mentioned below will perform the above-mentioned update with the help of the findOneAndUpdate() method.

> db.laptops.findOneAndUpdate({"Units": {$gte: 50}}, {$set: {"Status": "available"}})

Text Description automatically generated

Following observations are drawn from the above output:

The findOneAndUpdate() method returned the original document (before update).

As there are two documents that have “Units” value greater than or equal to “50“, but the findOneAndUpdate() method considers the first that matches the condition.

You can verify the update by using the command mentioned below: and it is noticed that only one document is added with the field “Status“.

> db.laptops.find().pretty()

Text Description automatically generated

Example 2: Returning the updated document

By default, the findOneAndUpdate() method returns the original document. You can get the updated document in return by setting the “returnNewDocument” option’s value to “true“.

The command written below will add a new field “cat” and its value is set to “Gaming“. The update is performed to the document where the “Price” value equals 1750. Moreover, the “returnNewDocument” value is “true“. So, it must return the updated document.

> db.laptops.findOneAndUpdate({"Price": 1750}, {$set: {"cat": "Gaming"}}, {returnNewDocument: true})

Text Description automatically generated

The output shows that the document returned by the above command is an updated version.

Example 3: Using findOneAndUpdate() method with options

Multiple options are supported by this method, as we have applied the “returnNewDocument” option in “Example 2“. In this section, several other options supported by this method are explained.

upsert: The value of the “upsert” option is false by default. And if it is set to “true“, the findOneAndUpdate() method will create a new document if the condition fails to match any document.

For instance, the below-mentioned command will look for the documents where the “Make” value matches “Alien” in the laptops collection. Since no document has a field value “Alien”, therefore, a new document will be created because we have set the “upsert” value as “true“.

Note: We have also used the “returnNewDocument” option to get the updated document in return.

> db.laptops.findOneAndUpdate({"Make": "Alien"}, {$set: {"Price": 1500,"cat": "Gaming"}}, {upsert: true, returnNewDocument: true})

Text Description automatically generated

maxTimeMS : This option is used to limit the time (in milliseconds) for the update command. If the specified time limit exceeds, the query will return an error. For instance, we have set the “maxTimeMS” option to value “2” in the below mentioned command:

> db.laptops.findOneAndUpdate({"Make": "Alien"}, {$set: {"Units": 15, "Price": 1850}}, {returnNewDocument: true, maxTimeMS: 2})

Text Description automatically generated

Note: The value of the “maxTimeMS” option must be numeric (not float or any other datatype).

Conclusion

The update process has a key role in any database management system because the data needs to be updated with time in any organization. Several update’s method extensions are used by MongoDB like findOneAndUpdate(). In this informative post, we have provided a brief application of this method in MongoDB. The targeted method matches the first document based on the condition and then updates the specific field(s) of that document.

About the author

Adnan Shabbir