- Data Models >
- Data Model Examples and Patterns >
- Model Specific Application Contexts >
- Model Data for Atomic Operations
Model Data for Atomic Operations¶
On this page
Although MongoDB supports multi-document transactions for replica sets (starting in version 4.0) and sharded clusters (starting in version 4.2), for many scenarios, the denormalized data model, as discussed on this page, will continue to be optimal for your data and use cases.
Pattern¶
In MongoDB, a write operation on a single document is atomic. For fields that must be updated together, embedding the fields within the same document ensures that the fields can be updated atomically.
For example, consider a situation where you need to maintain information on books, including the number of copies available for checkout as well as the current checkout information.
The available copies of the book and the checkout information should be
in sync. As such, embedding the available
field and the
checkout
field within the same document ensures that you can update
the two fields atomically.
Then to update with new checkout information, you can use the
db.collection.updateOne()
method to atomically update both
the available
field and the checkout
field:
The operation returns a document that contains information on the status of the operation:
The matchedCount
field shows that 1
document matched the update
condition, and modifiedCount
shows that the operation updated 1
document.
If no document matched the update condition, then matchedCount
and
modifiedCount
would be 0
and would indicate that you could not
check out the book.