Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js Driver

Compound Operations

On this page

  • Overview
  • Built-in Methods

Most database requests either read data from a database or write data into a database. However, there are instances where you may require a single operation that reads and writes data.

Compound operations combine read and write operations in a single atomic statement, so there's no chance of data changing in between a read and a subsequent write.

If you execute each operation separately, another request may alter the data between the read and write operations. These data changes may not prevent your operation from succeeding, but they can make error handling more difficult. When your application has to handle potential errors at any stage of the process, it can become brittle and difficult to test.

The Node.js driver provides the following methods to perform compound operations:

  • findOneAndDelete()

  • findOneAndUpdate()

  • findOneAndReplace()

These methods accept an optional options object with configurable sort and projection options.

You can also set the includeResultMetadata option to specify the return type of each of these methods. To learn more about this option, see the includeResultMetadata Option section of this guide.

The findOneAndUpdate() and findOneAndDelete() methods take the returnDocument setting, which specifies if the method returns the pre-update or post-update version of the modified document.

The includeResultMetadata option determines the return type of the compound methods.

This setting defaults to false, which means that each method returns the matched document. If no document is matched, each method returns null. If you set includeResultMetadata to true, the method returns a ModifyResult type that contains the found document and additional metadata.

Suppose a collection contains only the following document:

{ _id: 1, x: "on" }

The following table shows how the value of the includeResultMetadata option changes the return type of the findOneAndDelete() method:

Option Value
Syntax and Output
Default: false

Document matched

await coll.findOneAndDelete({ x: "on" });

No document matched

await coll.findOneAndDelete({ x: "off" });
await coll.findOneAndDelete({ x: "on" }, { includeResultMetadata: true });
←  Specify a QueryPromises →