Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Compound Operations

On this page

  • Overview
  • Built-in Methods

Most database requests only need to read data out of a database or write data into a database. However, client applications sometimes need to read and write data in a single interaction with the database.

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; in fact, both operations take place in the same line of code from the perspective of your client application.

This property can be useful in cases where you want to write to a specific document, but you haven't found it yet. If you just perform a read for the document's _id and then try to alter the document you just found, it's possible that someone else can alter the document in between your read and write operations. This doesn't stop you from doing this work, but it can make error handling much more difficult. Compound operations help keep your logic straightforward by handling that logic entirely inside the database behind a layer of abstraction, so you don't have to worry about it. While you can accomplish this task using separate reads and writes, doing so requires the client application to gracefully handle potential errors at any stage of the process and in multiple potential error states. This increases the complexity of your code and can make your client application brittle and difficult to test.

There are three major compound operations:

  • findOneAndDelete() matches multiple documents to a supplied query and removes the first of those matched documents.

  • findOneAndUpdate() matches multiple documents to a supplied query and updates the first of those matched documents using the provided update document.

  • findOneAndReplace() matches multiple documents to a supplied query and replaces the first of those matched documents using the provided replacement document.

All three methods accept an optional options object with configurable sort and projection options that work just like their read operation equivalents. findOneAndUpdate() and findOneAndDelete() allow the client to configure the returnDocument option, a boolean that determines if the method returns the pre-update or post-update version of the modified document.

←  Specify a QueryPromises and Callbacks →