JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Using findOneAndUpdate() method in MongoDB

Author:JIYIK Last Updated:2025/04/28 Views:

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


Using findOneAndUpdate() method in MongoDB

db.collection.findOneAndUpdate()Method updates the matching documents of a collection based on the selection criteria. If there are multiple documents matching, this method will update only the first document that matches the selection criteria.

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

This method returns the original document; however, if you want to return an updated document, you must specify a value of true for the returnNewDocument parameter.

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

grammar:

db.collection.findOneAndUpdate(

selection_criteria: <document>,

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

    sort: <document>,

    maxTimeMS: <number>,

    upsert: <boolean>,

    returnNewDocument: <boolean>,

    collation: <document>,

    arrayFilters: [ <filterdocument1>, … ]
})

parameter:

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

Optional parameters:

  1. projection: This parameter is of type Document. The projection parameter will determine which fields will be returned to the matching documents.

    This document uses the following values:

    { field1: <boolean>, field2: <boolean> ... }
    
    If the value of this field is 1 or true, it means that the field is included, and if the value of this field is 0 or false, it means that the field is excluded.
  2. sort: If the query selects multiple documents, this determines which document the operation will modify. db.collection.findOneAndUpdate()The method will update the first document in the sort order specified by this parameter.

    This parameter is of type Document.

  3. maxTimeMS: This parameter is of type number. It will specify the time limit in milliseconds within which the operation has to complete.

    If the time limit is exceeded, it will return an error.

  4. 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 this case, this method creates a new document.

    It returns null (after inserting a new document) unless the value of the returnNewDocument option is set to true. Alternatively, if the value of this upsert option is set to true, this method updates the documents that match the given filter query.

  5. returnNewDocument: This parameter type is a Boolean value. By default, this method will return the original document.

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

  6. Collation: It specifies the collation to be used for the operation. It allows the user to determine language-specific string comparison rules, such as rules for letter case and accents.

    This parameter is of type Document.

  7. arrayFilters: An array of filter documents indicating which array elements to modify for update operations on array fields. The type of this parameter is array.

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

In the following examples, you will use the following database. You will create a collection called students which contains documents containing student details.

The database is as follows:

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 matching document.

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

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

Here, you are updating the first matching document (i.e. {$inc:{score:4}}) based on the selection criteria (i.e. name: "Ali"). 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 an embedded document

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

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

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

Output:

findOneAndUpdate() Method 2


Use the findOneAndUpdate() method to update the first matching 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 are updating the first matching document based on the selection criteria (i.e. name: "Ali") by {$inc:{score:5}}increasing the value of the score field by five.

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

Output:

findOneAndUpdate() Method 3


Summarize

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

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Date comparison in MongoDB

Publish Date:2025/04/28 Views:169 Category:MongoDB

This MongoDB tutorial discusses the issue of returning Date-based queries. In addition, there is also a good tutorial on how to use Date Range queries in MongoDB. Using date ranges in MongoDB We will learn to write MongoDB date range querie

Find objects between two dates in MongoDB

Publish Date:2025/04/28 Views:94 Category:MongoDB

In this article, the problem of finding objects between two dates was briefly discussed. In addition, the operators $gte, $lte, $gt, and $lt used for this purpose were briefly explained in detail. Querying date ranges in MongoDB This sectio

Comparing Dates in MongoDB

Publish Date:2025/04/28 Views:115 Category:MongoDB

Date is a common field in most databases, and sometimes we need to find exact documents from a collection in MongoDB. For example, if we have a collection of orders, we might search for those documents before or after a specific date. In th

Convert string to date in MongoDB

Publish Date:2025/04/28 Views:162 Category:MongoDB

MongoDB is an excellent platform that is growing in popularity. Among the various features it offers, MongoDB also allows you to convert data from one type to another. This may seem like a complex function, but it is very simple to execute.

Building the MongoDB REST API

Publish Date:2025/04/28 Views:70 Category:MongoDB

MongoDB is a flexible and scalable document-oriented database system that is widely used for large-volume data storage. It uses documents and collections instead of the traditional rational database approach of using tables and rows. MongoD

Using ORM with MongoDB

Publish Date:2025/04/28 Views:117 Category:MongoDB

MongoDB introduces a NoSQL solution for data storage and management, consisting of documents represented in JSON style. Like other database systems, MongoDB can also use ORM. In this article, we will explain the concepts of ORM and general

Locking mechanism in MongoDB

Publish Date:2025/04/28 Views:95 Category:MongoDB

In database management systems, locking mechanisms ensure the consistency of the entire result. For example, if some writing process is in progress on the data, a read command cannot be executed at the same time. Database resources are lock

Unique Index in MongoDB

Publish Date:2025/04/28 Views:130 Category:MongoDB

In this article, you'll learn about unique indexes, including what they are and how to create them in MongoDB. Additionally, the process of making a user's email unique in MongoDB is briefly described. The contents of this article are as fo

Creating Indexes in MongoDB

Publish Date:2025/04/28 Views:178 Category:MongoDB

Indexes help resolve queries efficiently. Without indexes, MongoDB must iterate through every document in the collection to find the documents that match the query. It will waste time and require MongoDB to handle such information. Therefor

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial