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.尽管MongoDB支持副本集(从版本4.0开始)和分片集群(从版本4.2开始)的多文档事务,但对于许多场景,如本页所述,非规范化数据模型将继续适合您的数据和用例。
In MongoDB, a write operation on a single document is atomic. 在MongoDB中,对单个文档的写入操作是原子的。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.available
字段和checkout
字段可以确保可以原子地更新这两个字段。
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:db.collection.updateOne()
方法以原子方式更新可用字段和签出字段:
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.matchedCount
字段显示1
个文档符合更新条件,modifiedCount
显示操作更新了1
个文档。
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.matchedCount
和modifiedCount
将为0,并表示您无法签出该书。