Atomicity and Transactions

Atomicity

In MongoDB, a write operation is atomic on the level of a singledocument, even if the operation modifies multiple embedded documentswithin a single document.

Multi-Document Transactions

When a single write operation (e.g.db.collection.updateMany()) modifies multiple documents,the modification of each document is atomic, but the operation as awhole is not atomic.

When performing multi-document write operations, whether through asingle write operation or multiple write operations, otheroperations may interleave.

For situations that require atomicity of reads and writes to multipledocuments (in a single or multiple collections), MongoDB supportsmulti-document transactions:

  • In version 4.0, MongoDB supports multi-document transactions onreplica sets.
  • In version 4.2, MongoDB introduces distributed transactions,which adds support for multi-document transactions on shardedclusters and incorporates the existing support formulti-document transactions on replica sets.

For details regarding transactions in MongoDB, see theTransactions page.

Important

In most cases, multi-document transaction incurs a greaterperformance cost over single document writes, and theavailability of multi-document transactions should not be areplacement for effective schema design. For many scenarios, thedenormalized data model (embedded documents and arrays) will continue to be optimal for yourdata and use cases. That is, for many scenarios, modeling your dataappropriately will minimize the need for multi-documenttransactions.

For additional transactions usage considerations(such as runtime limit and oplog size limit), see alsoProduction Considerations.

Concurrency Control

Concurrency control allows multiple applications to run concurrentlywithout causing data inconsistency or conflicts.

One approach is to create a unique index on afield that can only have unique values. This prevents insertions orupdates from creating duplicate data. Create a unique index on multiplefields to force uniqueness on that combination of field values. Forexamples of use cases, see update() and Unique Index and findAndModify() and Unique Index.

Another approach is to specify the expected current value of a field inthe query predicate for the write operations.

See also

Read Isolation, Consistency, and Recency