On this page本页内容
In MongoDB, a write operation is atomic on the level of a single document, even if the operation modifies multiple embedded documents within a single document.在MongoDB中,写入操作在单个文档级别上是原子的,即使该操作修改单个文档中的多个嵌入文档也是如此。
When a single write operation (e.g. 当单个写入操作(例如db.collection.updateMany()
) modifies multiple documents, the modification of each document is atomic, but the operation as a whole is not atomic.db.collection.updateMany()
)修改多个文档时,每个文档的修改都是原子的,但整个操作不是原子的。
When performing multi-document write operations, whether through a single write operation or multiple write operations, other operations may interleave.执行多文档写入操作时,无论是通过单个写入操作还是通过多个写入操作,其他操作都可能交错。
For situations that require atomicity of reads and writes to multiple documents (in a single or multiple collections), MongoDB supports multi-document transactions:对于需要对多个文档(在单个或多个集合中)进行原子性读写的情况,MongoDB支持多文档事务:
For details regarding transactions in MongoDB, see the Transactions page.有关MongoDB中事务的详细信息,请参阅事务页面。
Important重要的
In most cases, multi-document transaction incurs a greater performance cost over single document writes, and the availability of multi-document transactions should not be a replacement for effective schema design. 在大多数情况下,多文档事务比单文档写入带来更大的性能成本,并且多文档事务的可用性不应取代有效的模式设计。For many scenarios, the denormalized data model (embedded documents and arrays) will continue to be optimal for your data and use cases. 对于许多场景,非规范化数据模型(嵌入式文档和数组)将继续适合您的数据和用例。That is, for many scenarios, modeling your data appropriately will minimize the need for multi-document transactions.也就是说,对于许多场景,适当地建模数据将最大限度地减少对多文档事务的需要。
For additional transactions usage considerations (such as runtime limit and oplog size limit), see also Production Considerations.有关其他事务使用注意事项(如运行时限制和oplog大小限制),请参阅生产注意事项。
Concurrency control allows multiple applications to run concurrently without causing data inconsistency or conflicts.并发控制允许多个应用程序并发运行,而不会导致数据不一致或冲突。
One approach is to create a unique index on a field that can only have unique values. 一种方法是在只能具有唯一值的字段上创建唯一索引。This prevents insertions or updates from creating duplicate data. 这可以防止插入或更新创建重复数据。Create a unique index on multiple fields to force uniqueness on that combination of field values. 在多个字段上创建唯一索引,以强制该字段值组合的唯一性。For examples of use cases, see update() and Unique Index and findAndModify() and Unique Index.有关用例的示例,请参阅update()
和唯一索引以及findAndModify()
和唯一索引。
Another approach is to specify the expected current value of a field in the query predicate for the write operations.另一种方法是在写操作的查询谓词中指定字段的预期当前值。