Introduction to MongoDB collection.findOneAndUpdate() Method

MongoDB is a non-relational database that supports various query and modification operations. Among them, the findOneAndUpdate() method can find and modify or update a document based on the query condition.

Syntax

The basic syntax of the findOneAndUpdate() method is as follows:

db.collection.findOneAndUpdate(
   <filter>,
   <update>,
   {
     projection: <document>,
     sort: <document>,
     maxTimeMS: <number>,
     upsert: <boolean>,
     returnDocument: <enum>,
     arrayFilters: [ <filterdocument1>, ... ],
     collation: <document>,
     hint:  <document|string>
   }
)

Parameter description:

  • filter: The query condition, the same as the query condition in the find() method.
  • update: The update operation, the same as the update operation in the update() and updateMany() methods.
  • projection: Optional parameter, specifies the fields to return.
  • sort: Optional parameter, specifies the sorting method.
  • maxTimeMS: Optional parameter, specifies the maximum execution time.
  • upsert: Optional parameter, if true, creates a new document when no corresponding document is found.
  • returnDocument: Optional parameter, specifies whether to return the document before or after the update.
  • arrayFilters: Optional parameter, used to update array type fields.
  • collation: Optional parameter, specifies the sorting rules.
  • hint: Optional parameter, specifies the index.

Use Cases

The findOneAndUpdate() method is usually used to modify or update documents, such as modifying user information, updating product inventory, etc. This method has atomicity and can execute both the query and modification operations in a single operation, avoiding concurrency issues in concurrent environments. In addition, the findOneAndUpdate() method also supports transaction operations, which can ensure the consistency of multiple operations.

Examples

The following example queries a document and changes its name field to “Alice”:

db.users.findOneAndUpdate(
  { _id: ObjectId("60b8919f06c40a1e7557d583") },
  { $set: { name: "Alice" } },
  { returnDocument: "after" }
)

After executing the above code, the updated document will be returned.

The following example queries a document and replaces “Bob” in its friends array with “David”:

db.users.findOneAndUpdate(
  { _id: ObjectId("60b8919f06c40a1e7557d583"), friends: "Bob" },
  { $set: { "friends.$": "David" } },
  { returnDocument: "after" }
)

After executing the above code, the updated document will be returned.

Conclusion

The findOneAndUpdate() method can find and modify or update a document based on the query condition. This method has atomicity and can execute both the query and modification operations in a single operation, avoiding concurrency issues in concurrent environments. In addition, this method also supports transaction operations.