category
type
status
date
slug
summary
tags
password
Property
Mar 29, 2023 01:40 PM
icon
MongoDB中对事务的支持
以下是MongoDB官方文档对MongoDB事务的解释:
- 在MongoDB中,对单个文档的操作是原子的。由于可以在单个文档结构中使用内嵌文档【embed document】和数组来获取数据之间的关系,而不必要跨多个文档和collection进行范式化,MongoDB这种单文档的原子性避免了许多实际场景中对多文档事务的需求。
- 对于那些需要多个文档(in a single or multiple collections)进行原子性读写的场景,MongoDB支持多文档事务【multiple document transaction】。而使用分布式事务,事务可以跨多个操作、集合【collection】、数据库、文档和分片使用。
Official document example, using callback API to implement transactions
- code by golang
- other version code by Open-IM-Server
Version restrictions
- In Version 4.0:MongoDB supports multi-document transaction on replica sets.【在副本集上支持多文档事务】
- In Version 4.2:MongoDB introduces distributed transaction【引入分布式事务】, which adds support for multiple document transactions on sharded clusters【分片集群】and incorporates【合并】the existing support for multiple document transactions on replica sets.
Multi-document transactions are atomic
i.e. provide an “all-or-nothing” proposition【提供全无或全有的语义】
- When a transaction commits, all data changes made in the transaction are saved and visible outside the transaction. That is, a transaction will not commit some of its changes while rolling back others.【事务不会在回滚其他更改时提交某些更改】Until a transaction commits, the data changes made in the transaction are not visible outside the transaction.
To be honest, the following description is a bit difficult to understand. 😐
However, when a transaction writes to multiple shards, not all outside read operations need to wait for the result of the committed transaction to be visible across the shards【不是所有读操作都需要等待已提交事务结果在分片中可见】. For example, if a transaction is committed and
write 1
is visible on shard A
but write 2
is not yet visible on shard B
, an outside read at concern “local”
can read the results of write 1
without seeing write 2
.- When a transaction aborts, all data changes made in the transaction are discarded【丢弃】without ever becoming visible【而不会变得可见】. For example, if any operation in the transaction fails, the transaction aborts and all data changes made in the transaction are discarded without ever becoming visible.
Disadvantages of multi-document transactions
- 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【反范式】, (such as embedded documents and arrays) will continue to be optimal for you data and use cases. 【依旧会是最适合你数据和用例】. That is, for many scenarios, modeling【建模】 your data appropriately【适当地】will minimize【减少(最大程度上)】 the need for multi-document transactions.
References
- official document
- The Chinese version of the official document. emm….but translation is not good
- 作者:axiszql
- 链接:https://axiszql.com/article/mongodb-learn-transaction
- 声明:本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。