Database Manual / Data Modeling / Data Model Examples and Patterns / Specific Application Contexts

Model Data for Atomic Operations原子操作的模型数据

Although MongoDB supports multi-document transactions for replica sets and sharded clusters, for many scenarios, the denormalized data model, as discussed on this page, will continue to be optimal for your data and use cases.尽管MongoDB支持副本集和分片集群的多文档事务,但在许多情况下,本页讨论的非规范化数据模型将继续适用于数据和用例。

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.在MongoDB中,对单个文档的写入操作是原子性的。对于必须一起更新的字段,将字段嵌入到同一文档中可以确保字段可以原子地更新。

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字段嵌入到同一文档中可以确保您可以原子地更新这两个字段。

{
_id: 123456789,
title: "MongoDB: The Definitive Guide",
author: [ "Kristina Chodorow", "Mike Dirolf" ],
published_date: ISODate("2010-09-24"),
pages: 216,
language: "English",
publisher_id: "oreilly",
available: 3,
checkout: [ { by: "joe", date: ISODate("2012-10-15") } ]
}

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()方法原子地更新available字段和checkout字段:

db.books.updateOne (
{ _id: 123456789, available: { $gt: 0 } },
{
$inc: { available: -1 },
$push: { checkout: { by: "abc", date: new Date() } }
}
)

The operation returns a document that contains information on the status of the operation:该操作返回一个包含操作状态信息的文档:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

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.如果没有文档符合更新条件,则matchedCountmodifiedCount将为0,表示您无法签出该书。