client_session – Logical sessions for sequential operations

Logical sessions for ordering sequential operations.

Requires MongoDB 3.6.

New in version 3.6.

Causally Consistent Reads

  1. with client.start_session(causal_consistency=True) as session:
  2. collection = client.db.collection
  3. collection.update_one({'_id': 1}, {'$set': {'x': 10}}, session=session)
  4. secondary_c = collection.with_options(
  5. read_preference=ReadPreference.SECONDARY)
  6.  
  7. # A secondary read waits for replication of the write.
  8. secondary_c.find_one({'_id': 1}, session=session)

If causal_consistency is True (the default), read operations that usethe session are causally after previous read and write operations. Using acausally consistent session, an application can read its own writes and isguaranteed monotonic reads, even when reading from replica set secondaries.

See also

The MongoDB documentation on

causal-consistency

Transactions

MongoDB 4.0 adds support for transactions on replica set primaries. Atransaction is associated with a ClientSession. To start a transactionon a session, use ClientSession.start_transaction() in a with-statement.Then, execute an operation within the transaction by passing the session to theoperation:

  1. orders = client.db.orders
  2. inventory = client.db.inventory
  3. with client.start_session() as session:
  4. with session.start_transaction():
  5. orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
  6. inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}},
  7. {"$inc": {"qty": -100}}, session=session)

Upon normal completion of with session.start_transaction() block, thetransaction automatically calls ClientSession.commit_transaction().If the block exits with an exception, the transaction automatically callsClientSession.abort_transaction().

For multi-document transactions, you can only specify read/write (CRUD)operations on existing collections. For example, a multi-document transactioncannot include a create or drop collection/index operations, including aninsert operation that would result in the creation of a new collection.

A session may only have a single active transaction at a time, multipletransactions on the same session can be executed in sequence.

New in version 3.7.

Sharded Transactions

PyMongo 3.9 adds support for transactions on sharded clusters running MongoDB4.2. Sharded transactions have the same API as replica set transactions.When running a transaction against a sharded cluster, the session ispinned to the mongos server selected for the first operation in thetransaction. All subsequent operations that are part of the same transactionare routed to the same mongos server. When the transaction is completed, byrunning either commitTransaction or abortTransaction, the session is unpinned.

New in version 3.9.

See also

The MongoDB documentation on

transactions

Classes

  • class pymongo.clientsession.ClientSession(_client, server_session, options, authset, implicit)
  • A session for ordering sequential operations.

    • abort_transaction()
    • Abort a multi-statement transaction.

New in version 3.7.

  • advancecluster_time(_cluster_time)
  • Update the cluster time for this session.

Parameters:

  1. - _cluster_time_: The[<code>cluster_time</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.client_session.ClientSession.cluster_time) fromanother _ClientSession_ instance.
  • advanceoperation_time(_operation_time)
  • Update the operation time for this session.

Parameters:

  1. - _operation_time_: The[<code>operation_time</code>](https://api.mongodb.com/python/current/api/pymongo/#pymongo.client_session.ClientSession.operation_time) fromanother _ClientSession_ instance.
  • client
  • The MongoClient this session wascreated from.

  • cluster_time

  • The cluster time returned by the last operation executedin this session.

  • commit_transaction()

  • Commit a multi-statement transaction.

New in version 3.7.

  • end_session()
  • Finish this session. If a transaction has started, abort it.

It is an error to use the session after the session has ended.

  • has_ended
  • True if this session is finished.

  • operation_time

  • The operation time returned by the last operation executedin this session.

  • options

  • The SessionOptions this session was created with.

  • session_id

  • A BSON document, the opaque server session identifier.

  • starttransaction(_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.

Changed in version 3.9: Added the max_commit_time_ms option.

New in version 3.7.

  • withtransaction(_callback, read_concern=None, write_concern=None, read_preference=None, max_commit_time_ms=None)
  • Execute a callback in a transaction.

This method starts a transaction on this session, executes callbackonce, and then commits the transaction. For example:

  1. def callback(session):
  2. orders = session.client.db.orders
  3. inventory = session.client.db.inventory
  4. orders.insert_one({"sku": "abc123", "qty": 100}, session=session)
  5. inventory.update_one({"sku": "abc123", "qty": {"$gte": 100}},
  6. {"$inc": {"qty": -100}}, session=session)
  7.  
  8. with client.start_session() as session:
  9. session.with_transaction(callback)

To pass arbitrary arguments to the callback, wrap your callablewith a lambda like this:

  1. def callback(session, custom_arg, custom_kwarg=None):
  2. # Transaction operations...
  3.  
  4. with client.start_session() as session:
  5. session.with_transaction(
  6. lambda s: callback(s, "custom_arg", custom_kwarg=1))

In the event of an exception, with_transaction may retry the commitor the entire transaction, therefore callback may be invokedmultiple times by a single call to with_transaction. Developersshould be mindful of this possiblity when writing a callback thatmodifies application state or has any other side-effects.Note that even when the callback is invoked multiple times,with_transaction ensures that the transaction will be committedat-most-once on the server.

The callback should not attempt to start new transactions, butshould simply run operations meant to be contained within atransaction. The callback should also not commit the transaction;this is handled automatically by with_transaction. If thecallback does commit or abort the transaction without error,however, with_transaction will return without taking furtheraction.

When callback raises an exception, with_transactionautomatically aborts the current transaction. When callback orcommit_transaction() raises an exception thatincludes the "TransientTransactionError" error label,with_transaction starts a new transaction and re-executesthe callback.

When commit_transaction() raises an exception withthe "UnknownTransactionCommitResult" error label,with_transaction retries the commit until the result of thetransaction is known.

This method will cease retrying after 120 seconds has elapsed. Thistimeout is not configurable and any exception raised by thecallback or by ClientSession.commit_transaction() after thetimeout is reached will be re-raised. Applications that desire adifferent timeout duration should not use this method.

Parameters:

  1. - _callback_: The callable <code>callback</code> to run inside a transaction.The callable must accept a single argument, this session. Note,under certain error conditions the callback may be run multipletimes.
  2. - _read_concern_ (optional): The[<code>ReadConcern</code>]($ba6aec8e2bd5e77f.md#pymongo.read_concern.ReadConcern) to use for thistransaction.
  3. - _write_concern_ (optional): The[<code>WriteConcern</code>]($1c33c29d27c9df5c.md#pymongo.write_concern.WriteConcern) to use for thistransaction.
  4. - _read_preference_ (optional): The read preference to use for thistransaction. If <code>None</code> (the default) the <code>read_preference</code>of this <code>Database</code> is used. See[<code>read_preferences</code>]($4f651614045067e6.md#module-pymongo.read_preferences) for options.Returns:

The return value of the callback.

New in version 3.9.

  • class pymongo.clientsession.SessionOptions(_causal_consistency=True, default_transaction_options=None)
  • Options for a new ClientSession.

Parameters:

  • causal_consistency (optional): If True (the default), readoperations are causally ordered within the session.
  • default_transaction_options (optional): The defaultTransactionOptions to use for transactions started on this session.
  • causal_consistency
  • Whether causal consistency is configured.

  • default_transaction_options

  • The default TransactionOptions to use for transactions started onthis session.

New in version 3.7.

  • class pymongo.clientsession.TransactionOptions(_read_concern=None, write_concern=None, read_preference=None, max_commit_time_ms=None)
  • Options for ClientSession.start_transaction().

Parameters:

  • read_concern (optional): TheReadConcern to use for this transaction.If None (the default) the read_preference ofthe MongoClient is used.
  • write_concern (optional): TheWriteConcern to use for thistransaction. If None (the default) the read_preference ofthe MongoClient is used.
  • read_preference (optional): The read preference to use. IfNone (the default) the read_preference of thisMongoClient is used. See read_preferencesfor options. Transactions which read must usePRIMARY.
  • max_commit_time_ms (optional): The maximum amount of time to allow asingle commitTransaction command to run. This option is an alias formaxTimeMS option on the commitTransaction command. If None (thedefault) maxTimeMS is not used.

Changed in version 3.9: Added the max_commit_time_ms option.

New in version 3.7.

  • max_commit_time_ms
  • The maxTimeMS to use when running a commitTransaction command.

New in version 3.9.