事务
Overview
在本指南中,您可以学习;了解如何使用PyMongo驾驶员执行事务。 事务允许您运行一系列操作,这些操作在提交ACID 事务之前不会更改任何数据。 如果ACID 事务中的任何操作返回错误,驾驶员就会取消ACID 事务,并在所有数据更改变得可见之前将其丢弃。
在MongoDB中,事务在逻辑会话中运行。会话是您打算按顺序运行的一组相关读取或写入操作。会话允许您在符合ACID的ACID 事务中运行操作,该ACID 事务满足原子性、一致性、隔离性和持久性的预期。 MongoDBACID 一致性保证ACID 事务操作中涉及的数据保持一致,即使操作遇到意外错误。
使用PyMongo时,您可以从 MongoClient
实例创建一个新会话,并将其类型定义为ClientSession
。 我们建议您将MongoClient
重复用于多个会话和事务,而不是每次都创建一个新客户端。
警告
仅应将 ClientSession
与创建它的 MongoClient
(或关联的 MongoDatabase
或 MongoCollection
)一起使用。将 ClientSession
与其他 MongoClient
一起使用会导致操作错误。
因果一致性(Causal Consistency)
MongoDB在客户端会话中实现因果一致性。因果一致性模型ACID 一致性保证会话中的操作按因果顺序运行。客户端观察到的结果与因果关系或操作之间的依赖关系一致。示例,如果您执行一系列操作,其中一个操作在逻辑上依赖于另一个操作的结果,则任何后续读取都会反映这种依赖关系。
下表描述了因果一致会话提供的ACID 一致性保证:
保证 | 说明 |
---|---|
读取写入操作 | 读取操作会反映之前写入操作的结果。 |
单调读取 | 读取操作不会返回反映比先前读取操作更早的数据状态的结果。 |
单调写入 | 如果写入操作必须先于其他写入操作,驾驶员会先运行此写入操作。 示例,如果调用 |
读取后写入 | 如果写入操作必须在其他读取操作之后进行,驾驶员会先运行读取操作。 示例,如果您调用 |
在因果一致会话中, MongoDB确保以下操作之间的因果关系:
具有
majority
读关注(read concern)的读取操作有
majority
写关注(write concern)的写入操作
提示
要学习;了解有关本节中提到的概念的更多信息,请参阅以下MongoDB Server手册条目:
样本数据
sample_restaurants.restaurants
本指南中的示例使用Atlas示例数据集中的 集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅 PyMongo入门教程。
方法
使用start_session()
方法启动会话后,可以使用返回的ClientSession
提供的以下方法管理会话状态:
方法 | 说明 |
---|---|
| Starts a new transaction, configured with the given options, on
this session. Returns an error if there is already
a transaction in progress for the session. To learn more about
this method, see the startTransaction() page in the Server manual. Parameters: read_concern , write_concern , read_preference , max_commit_time_ms Return Type: ContextManager |
| Ends the active transaction for this session. Returns an
error if there is no active transaction for the session or the
transaction has been committed or ended. To learn more about
this method, see the abortTransaction() page in the Server manual. |
| Commits the active transaction for this session. Returns an
error if there is no active transaction for the session or if the
transaction was ended. To learn more about
this method, see the commitTransaction() page in the Server manual. |
| Starts a transaction on this session and runs callback once, then
commits the transaction. In the event of an exception, this method may retry
the commit or the entire transaction, which may invoke the callback multiple
times by a single call to with_transaction() .Parameters: callback , read_concern , write_concern , read_preference , max_commit_time_ms Return Value: The result of the callback function |
| Finishes this session. If a transaction has started, this method aborts it.
Returns an error if there is no active session to end. |
ClientSession
还提供检索会话属性和修改可变会话属性的方法。 要学习;了解有关这些方法的更多信息,请参阅API文档。
例子
以下示例显示如何通过以下步骤创建会话、创建事务以及提交多文档插入操作:
使用
start_session()
方法从客户端创建会话。使用
with_transaction()
方法启动事务。插入多个文档。
with_transaction()
方法运行插入操作并提交ACID 事务。 如果任何操作导致错误,with_transaction()
将取消该ACID 事务。 此方法可确保在区块退出时正确关闭会话。使用
client.close()
方法关闭与服务器的连接。
# Establishes a connection to the MongoDB server client = MongoClient("<connection string>") # Defines the database and collection restaurants_db = client["sample_restaurants"] restaurants_collection = restaurants_db["restaurants"] # Function performs the transaction def insert_documents(session): restaurants_collection_with_session = restaurants_collection.with_options( write_concern=WriteConcern("majority"), read_concern=ReadConcern("local") ) # Inserts documents within the transaction restaurants_collection_with_session.insert_one( {"name": "PyMongo Pizza", "cuisine": "Pizza"}, session=session ) restaurants_collection_with_session.insert_one( {"name": "PyMongo Burger", "cuisine": "Burger"}, session=session ) # Starts a client session with client.start_session() as session: try: # Uses the with_transaction method to start a transaction, execute the callback, and commit (or abort on error). session.with_transaction(insert_documents) print("Transaction succeeded") except (ConnectionFailure, OperationFailure) as e: print(f"Transaction failed: {e}") # Closes the client connection client.close()
如果需要更好地控制事务,可以使用start_transaction()
方法。 您可以将此方法与上一节中描述的commit_transaction()
和abort_transaction()
方法结合使用,以手动管理ACID 事务生命周期。
更多信息
要了解有关本指南中提到的概念的更多信息,请参阅服务器手册中的以下页面:
要学习;了解有关ACID compliance的更多信息,请参阅什么是数据库管理系统中的ACID属性? MongoDB网站上的文章。
API 文档
要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档: