AsyncIOMotorClientSession – Sequence of operations¶
Warning
Motor will be deprecated on May 14th, 2026, one year after the production release of the PyMongo Async driver. Critical bug fixes will be made until May 14th, 2027. We strongly recommend that Motor users migrate to the PyMongo Async driver while Motor is still supported. To learn more, see the migration guide.
- class motor.motor_asyncio.AsyncIOMotorClientSession(delegate, motor_client)¶
-
- coroutine end_session() None¶
Finish this session. If a transaction has started, abort it.
It is an error to use the session after the session has ended.
- start_transaction(read_concern=None, write_concern=None, read_preference=None, max_commit_time_ms=None)¶
Start a multi-statement transaction.
Takes the same arguments as
TransactionOptions.Best used in a context manager block:
# Use "await" for start_session, but not for start_transaction. async with await client.start_session() as s: async with s.start_transaction(): await collection.delete_one({"x": 1}, session=s) await collection.insert_one({"x": 2}, session=s)
- async with_transaction(coro, read_concern=None, write_concern=None, read_preference=None, max_commit_time_ms=None)¶
Executes an awaitable in a transaction.
This method starts a transaction on this session, awaits
coroonce, and then commits the transaction. For example:async def coro(session): orders = session.client.db.orders inventory = session.client.db.inventory inserted_id = await orders.insert_one( {"sku": "abc123", "qty": 100}, session=session) await inventory.update_one( {"sku": "abc123", "qty": {"$gte": 100}}, {"$inc": {"qty": -100}}, session=session) return inserted_id async with await client.start_session() as session: inserted_id = await session.with_transaction(coro)
To pass arbitrary arguments to the
coro, wrap it with alambdalike this:async def coro(session, custom_arg, custom_kwarg=None): # Transaction operations... async with await client.start_session() as session: await session.with_transaction( lambda s: coro(s, "custom_arg", custom_kwarg=1))
In the event of an exception,
with_transactionmay retry the commit or the entire transaction, thereforecoromay be awaited multiple times by a single call towith_transaction. Developers should be mindful of this possibility when writing acorothat modifies application state or has any other side-effects. Note that even when thecorois invoked multiple times,with_transactionensures that the transaction will be committed at-most-once on the server.The
coroshould not attempt to start new transactions, but should simply run operations meant to be contained within a transaction. Thecoroshould also not commit the transaction; this is handled automatically bywith_transaction. If thecorodoes commit or abort the transaction without error, however,with_transactionwill return without taking further action.When
cororaises an exception,with_transactionautomatically aborts the current transaction. Whencoroorcommit_transaction()raises an exception that includes the"TransientTransactionError"error label,with_transactionstarts a new transaction and re-executes thecoro.When
commit_transaction()raises an exception with the"UnknownTransactionCommitResult"error label,with_transactionretries the commit until the result of the transaction is known.This method will cease retrying after 120 seconds has elapsed. This timeout is not configurable and any exception raised by the
coroor byClientSession.commit_transaction()after the timeout is reached will be re-raised. Applications that desire a different timeout duration should not use this method.- Parameters:
coro: The coroutine to run inside a transaction. The coroutine must accept a single argument, this session. Note, under certain error conditions the coroutine may be run multiple times.
read_concern (optional): The
ReadConcernto use for this transaction.write_concern (optional): The
WriteConcernto use for this transaction.read_preference (optional): The read preference to use for this transaction. If
None(the default) theread_preferenceof thisDatabaseis used. Seeread_preferencesfor options.
- Returns:
The return value of the
coro.
Added in version 2.1.
- property advance_cluster_time¶
Update the cluster time for this session.
- Parameters:
cluster_time – The
cluster_timefrom another ClientSession instance.
- property advance_operation_time¶
Update the operation time for this session.
- Parameters:
operation_time – The
operation_timefrom another ClientSession instance.
- property client¶
The
MotorClientthis session was created from.
- property cluster_time¶
The cluster time returned by the last operation executed in this session.
- property has_ended¶
True if this session is finished.
- property in_transaction¶
True if this session has an active multi-statement transaction.
Added in version 3.10.
- property operation_time¶
The operation time returned by the last operation executed in this session.
- property options¶
The
SessionOptionsthis session was created with.
- property session_id¶
A BSON document, the opaque server session identifier.