Docs 菜单
Docs 主页
/ / /
Pymongo 驱动程序
/

事务

在此页面上

  • Overview
  • 因果一致性(Causal Consistency)
  • 样本数据
  • 方法
  • 例子
  • 更多信息
  • API 文档

在本指南中,您可以学习;了解如何使用PyMongo驾驶员执行事务。 事务允许您运行一系列操作,这些操作在提交ACID 事务之前不会更改任何数据。 如果ACID 事务中的任何操作返回错误,驾驶员就会取消ACID 事务,并在所有数据更改变得可见之前将其丢弃。

在MongoDB中,事务在逻辑会话中运行。会话是您打算按顺序运行的一组相关读取或写入操作。会话允许您在符合ACID的ACID 事务中运行操作,该ACID 事务满足原子性、一致性、隔离性和持久性的预期。 MongoDBACID 一致性保证ACID 事务操作中涉及的数据保持一致,即使操作遇到意外错误。

使用PyMongo时,您可以从 MongoClient实例创建一个新会话,并将其类型定义为ClientSession 。 我们建议您将MongoClient重复用于多个会话和事务,而不是每次都创建一个新客户端。

警告

仅应将 ClientSession 与创建它的 MongoClient(或关联的 MongoDatabaseMongoCollection)一起使用。将 ClientSession 与其他 MongoClient 一起使用会导致操作错误。

MongoDB在客户端会话中实现因果一致性。因果一致性模型ACID 一致性保证会话中的操作按因果顺序运行。客户端观察到的结果与因果关系或操作之间的依赖关系一致。示例,如果您执行一系列操作,其中一个操作在逻辑上依赖于另一个操作的结果,则任何后续读取都会反映这种依赖关系。

下表描述了因果一致会话提供的ACID 一致性保证:

保证
说明

读取写入操作

读取操作会反映之前写入操作的结果。

单调读取

读取操作不会返回反映比先前读取操作更早的数据状态的结果。

单调写入

如果写入操作必须先于其他写入操作,驾驶员会先运行此写入操作。

示例,如果调用 insert_one() 插入文档,然后调用 update_one() 修改插入的文档,驾驶员会先运行插入操作。

读取后写入

如果写入操作必须在其他读取操作之后进行,驾驶员会先运行读取操作。

示例,如果您调用 find() 来检索文档,然后调用 delete_one() 来删除检索到的文档,则驾驶员会先运行查找操作。

在因果一致会话中, MongoDB确保以下操作之间的因果关系:

  • 具有 majority读关注(read concern)的读取操作

  • majority写关注(write concern)的写入操作

提示

要学习;了解有关本节中提到的概念的更多信息,请参阅以下MongoDB Server手册条目:

  • 因果一致性(Causal Consistency)

  • 因果一致性以及读关注和写关注

sample_restaurants.restaurants本指南中的示例使用Atlas示例数据集中的 集合。要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅 PyMongo入门教程。

使用start_session()方法启动会话后,可以使用返回的ClientSession提供的以下方法管理会话状态:

方法
说明

start_transaction()

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

abort_transaction()

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.

commit_transaction()

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.

with_transaction()

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

end_session()

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文档。

以下示例显示如何通过以下步骤创建会话、创建事务以及提交多文档插入操作:

  1. 使用 start_session() 方法从客户端创建会话。

  2. 使用 with_transaction() 方法启动事务。

  3. 插入多个文档。 with_transaction()方法运行插入操作并提交ACID 事务。 如果任何操作导致错误, with_transaction()将取消该ACID 事务。 此方法可确保在区块退出时正确关闭会话。

  4. 使用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 事务生命周期。

注意

不支持并行操作

PyMongo不支持在单个ACID 事务中运行并行操作。

如果您使用的是MongoDB Server v8.0 或更高版本,则可以通过在bulk_write() 实例上调用 方法,在单个ACIDMongoClient 事务中对多个命名空间执行写入操作。有关更多信息,请参阅批量写入操作指南。

要了解有关本指南中提到的概念的更多信息,请参阅服务器手册中的以下页面:

要学习;了解有关ACID compliance的更多信息,请参阅什么是数据库管理系统中的ACID属性? MongoDB网站上的文章。

要进一步了解本指南所讨论的任何类型或方法,请参阅以下 API 文档:

后退

存储大文件