How to Use the findOneAndUpdate() Method in MongoDB

Tahseen Tauseef Feb 15, 2024
  1. Use the findOneAndUpdate() Method in MongoDB
  2. Use the findOneAndUpdate() Method to Update the First Matched Document
  3. Use the findOneAndUpdate() Method to Update the Value of the Embedded Document
  4. Use the findOneAndUpdate() Method to Update the First Matched Document and Return the Updated Document
  5. Conclusion
How to Use the findOneAndUpdate() Method in MongoDB

This article will introduce the the findOneAndUpdate() method in MongoDB. We will use this method to update the first matched and embedded documents.

Use the findOneAndUpdate() Method in MongoDB

The method db.collection.findOneAndUpdate() updates the collection’s matching document according to a selection criteria. This method will only update the first document that matches the selection criteria if there are more than one document matches.

The value of the _id field does not change when you update the document.

This method will return the original document; however, you must specify the value of the returnNewDocument parameter to true if you want the updated document to be returned.

You can use this method to replace embedded documents. This approach can also be used in multi-document transactions.

Syntax:

db.collection.findOneAndUpdate(

selection_criteria: <document>,

update_data: <document>,
{
   projection: <document>,

    sort: <document>,

    maxTimeMS: <number>,

    upsert: <boolean>,

    returnNewDocument: <boolean>,

    collation: <document>,

    arrayFilters: [ <filterdocument1>,  ]
})

Parameters:

  1. The first parameter, selection_criteria, is the selection criteria for the update. The type for this parameter is a document.
  2. The second parameter, update_data, is a document to be updated. The type for this parameter is a document.
  3. The third parameter is optional.

Optional Parameters:

  1. projection: The type for this parameter is a document. The projection parameter will determine which fields are returned to the matching documents.

    This document takes the following values:

    { field1: <boolean>, field2: <boolean> ... }
    

    If the field’s value is 1 or true, it indicates that the field is included, and if the field’s value is 0 or false, the field is excluded.

  1. sort: This will determine which document the operation will modify if the query selects multiple documents. The db.collection.findOneAndUpdate() method will update the first document in the sort order specified by this argument.

    The type for this parameter is a document.

  2. maxTimeMS: The type for this parameter is number. It will specify the time limit in milliseconds within which the operation must be complete.

    It will return an error if the time limit is exceeded.

  3. upsert: The default value of this parameter is false.

    Suppose the value of this option is set to true and no document matches the given filter query. In that case, this method creates a new document.

    It returns a null value (after inserting a new document) unless the value of the returnNewDocument option is set to be true. Or if the value for this upsert option is set to be true, then this method will update the document that matches the given filter query.

  4. returnNewDocument: This parameter type is a boolean. By default, this method will return the original document.

    Use the returnNewDocument parameter and set its value to true to return the updated document.

  5. Collation: It specifies the use of the collation for operations. It allows users to determine the language-specific rules for string comparison, like rules for letter cases and accent marks.

    The type for this parameter is a document.

  6. arrayFilters: An array of filter documents indicates which array elements are to be modified for an update operation on an array field. The type for this parameter is an array.

It will return the original document, but if you want to return the updated document, you will have to set the value of the returnNewDocument parameter to true.

In the following examples, you will work with the following database. You will create a collection called students with documents containing the students’ details.

The database is given below:

db={
  "students": [
    {
      id: 1,
      name: "Ali",
      language: "JavaScript",
      score: 82
    },
    {
      id: 2,
      name: "Haris",
      language: "Python",
      score: 91
    },
    {
      id: 3,
      name: "Hamza",
      language: "Python",
      score: {
        "Physics": 84,
        "Math": 85
      }
    }
  ]
}

Use the findOneAndUpdate() Method to Update the First Matched Document

For this example, you will use the query given below:

db.students.findOneAndUpdate({name:"Ali"},{$inc:{score:4}})

Here, you will update the first matched document according to the selection criteria (i.e., name: "Ali") by a new document (i.e., {$inc:{score:4}}. The value of the score field is increased by four, and it returns the original document.

Output:

findOneAndUpdate() Method

After updating the document, it will return this output.

Use the findOneAndUpdate() Method to Update the Value of the Embedded Document

For this example, you will use the query given below:

db.student.findOneAndUpdate({name:"Hamza"},{$inc:{"score.Math":5}})

Here, you will update the value of the Math field in the embedded document. The value of the Math field is increased by five.

Output:

findOneAndUpdate() Method 2

Use the findOneAndUpdate() Method to Update the First Matched Document and Return the Updated Document

For this example, you will use the query given below:

 db.student.findOneAndUpdate({name:"Ali"},{$inc:{score:5}},{returnNewDocument:true})

Here, you will update the first matched document according to the selection criteria (i.e., name: "Ali") by a new document (i.e., {$inc:{score:5}}. The value of the score field is increased by five.

It returns the newly updated document because we set the value of the returnNewDocument to true.

Output:

findOneAndUpdate() Method 3

Conclusion

Through the help of this MongoDB tutorial article, you have learned how to use the db.collection.findOneAndUpdate() method, which is used to update the first matched document in the collection that matches the selection criteria. You can also use this method to replace embedded documents and also use it in multi-document transactions.

Related Article - MongoDB Method