This version of the documentation is archived and no longer supported. To learn how to upgrade your version of PHP Library Manual, refer to the upgrade documentation.


New in version 1.5.



Execute a callback within a transaction using the given client session

function with_transaction(MongoDB\Driver\Session $session, callable $callback, array $transactionOptions = []): void

This method has the following parameters:

Parameter Type Description
$session MongoDB\Driver\Session A client session used to execute the transaction.
$callback callback A callback that will be run inside the transaction. The callback must accept a MongoDB\Driver\Session object as first argument.
$transactionOptions array Optional. Transaction options, which will be passed to MongoDB\Driver\Session::startTransaction. See the extension documentation for a list of supported options.


This function is responsible for starting a transaction, invoking a callback, and committing a transaction. It also applies logic to retry this process after certain errors within a preset time limit. The callback is expected to execute one or more operations within the transactionby passing the callback’s MongoDB\Driver\Session argument as an option to those operations; however, that is not enforced.


Applications are strongly encouraged to use an idempotent callback, since it may be invoked multiple times if retryable errors are encountered during either callback execution or committing.

Any exception thrown during execution of the callback will be caught and evaluated. If an exception has a TransientTransactionError error label, the transaction will be aborted, restarted, and the callback will be invoked again. For any other exception, the transaction will be aborted and the exception re-thrown to propagate the error to the caller of with_transaction().

Following successful execution of the callback, the transaction will be committed. If an exception with an UnknownTransactionCommitResult error label is encountered, the commit will be retried. If an exception with a TransientTransactionError error label is encountered, the transaction will be restarted and control will return to invoking the callback. Any other exception will be re-thrown to propagate the error to the caller of with_transaction().

When an error occurs during callback execution or committing, the process is only retried if fewer than 120 seconds have elapsed since with_transaction() was first called. This time limit is not configurable. After this time, any exception that would normally result in a retry attempt will instead be re-thrown.


MongoDB\Exception\InvalidArgumentException for errors related to the parsing of parameters or options.

MongoDB\Driver\Exception\RuntimeException for other errors at the driver level (e.g. connection errors).