Docs Menu
Docs Home
/
PHP Library Manual
/

Perform a Transaction

In this guide, you can learn how to use the MongoDB PHP Library to perform transactions. Transactions allow you to perform a series of operations that change data only if the entire transaction is committed. If any operation in the transaction does not succeed, the library stops the transaction and discards all data changes before they ever become visible. This feature is called atomicity.

In MongoDB, transactions run within logical sessions. A session is a grouping of related read or write operations that you want to run sequentially. Sessions enable causal consistency for a group of operations and allow you to run operations in an ACID-compliant transaction, which is a transaction that meets an expectation of atomicity, consistency, isolation, and durability. MongoDB guarantees that the data involved in your transaction operations remains consistent, even if the operations encounter unexpected errors.

When using the MongoDB PHP Library, you can create a new session from a MongoDB\Client instance. Then, you can use the resulting MongoDB\Driver\Session instance to perform transactions.

Warning

Use a Session only in operations running on the Client that created it. Using a Session with a different Client results in operation errors.

MongoDB enables causal consistency in certain client sessions. The causal consistency model guarantees that in a distributed system, operations within a session run in a causal order. Clients observe results that are consistent with the causal relationships, or the dependencies between operations. For example, if you perform a series of operations where one operation logically depends on the result of another, any subsequent reads reflect the dependent relationship.

To guarantee causal consistency, client sessions must fulfill the following requirements:

  • When starting a session, the driver must enable the causal consistency option. This option is enabled by default.

  • Operations must run in a single session on a single thread. Otherwise, the sessions or threads must communicate the operation time and cluster time values to each other. To view an example of two sessions that communicate these values, see the Causal Consistency examples in the MongoDB Server manual.

  • You must use a majority read concern.

  • You must use a majority write concern. This is the default write concern value.

The following table describes the guarantees that causally consistent sessions provide:

Guarantee
Description

Read your writes

Read operations reflect the results of preceding write operations.

Monotonic reads

Read operations do not return results that reflect an earlier data state than a preceding read operation.

Monotonic writes

If a write operation must precede other write operations, the server runs this write operation first.

For example, if you call MongoDB\Collection::insertOne() to insert a document, then call MongoDB\Collection::updateOne() to modify the inserted document, the server runs the insert operation first.

Writes follow reads

If a write operation must follow other read operations, the server runs the read operations first.

For example, if you call MongoDB\Collection::findOne() to retrieve a document, then call MongoDB\Collection::deleteOne() to delete the retrieved document, the server runs the find operation first.

Tip

To learn more about the concepts mentioned in this section, see the following MongoDB Server manual entries:

In this section, you can learn about the transaction APIs provided by the MongoDB PHP Library. Before you begin a transaction, you must create a Session by using the MongoDB\Client::startSession() method on your Client instance. Then, you can use either of the following APIs to perform a transaction:

The MongoDB PHP Library provides a Convenient Transaction API to manage the transaction lifecyle. Implement this API by using the MongoDB\with_transaction() function to run custom callback within a transaction. The with_transaction() function performs the following tasks:

  • Starts the transaction

  • Handles errors by either ending the transaction or retrying it, such as when the operation returns a TransientTransactionError

  • Commits the transaction

The Transaction Example section of this guide demonstrates how to use this API to perform a transaction.

Alternatively, you can have more control over your transaction lifecyle by using the methods provided by the Session class. The following table describes these methods:

Method
Description

startTransaction()

Starts a new transaction on this session. The session must be passed into each operation within the transaction, or the operation will run outside of the transaction.

You can set transaction options by passing an options parameter.

commitTransaction()

Commits the active transaction for this session. This method returns an error if there is no active transaction for the session, the transaction was previously ended, or if there is a write conflict.

abortTransaction()

Ends the active transaction for this session. This method returns an error if there is no active transaction for the session or if the transaction was committed or ended.

This example defines a callback function that modifies data in the collections of the bank database for a banking transaction. The code performs the following actions:

  • Creates Collection instances to access the target collections.

  • Specifies the account number and amount to be transferred between accounts.

  • Defines the callback function, which receives the Session instance as a parameter.

  • Updates the customer's balances to reflect the money transfer.

  • Records a receipt of the transaction with a timestamp.

  • Prints a message if the transaction committed successfully.

$receipts = $client->bank->receipts;
$checking = $client->bank->checking_accounts;
$saving = $client->bank->saving_accounts;
$accountId = '5678';
$transferAmount = 1000.0;
$callback = function (MongoDB\Driver\Session $session) use (
$checking,
$saving,
$receipts,
$accountId,
$transferAmount,
): void {
$checking->updateOne(
['account_id' => $accountId],
['$inc' => ['balance' => -$transferAmount]],
['session' => $session],
);
$saving->updateOne(
['account_id' => $accountId],
['$inc' => ['balance' => $transferAmount]],
['session' => $session],
);
$summary = sprintf('SAVINGS +%1$u CHECKING -%1$u', $transferAmount);
$receipts->insertOne(
[
'account_id' => $accountId,
'summary' => $summary,
'timestamp' => new MongoDB\BSON\UTCDateTime(),
],
['session' => $session],
);
echo 'Successfully performed transaction!', PHP_EOL;
echo 'Summary: ', $summary, PHP_EOL;
};

Then, run the following code to perform the transaction. This code completes the following actions:

  1. Creates a session from the client by using the startSession() method.

  2. Calls the with_transaction() function to manage the transaction, passing the session and the callback as parameters.

$session = $client->startSession();
try {
MongoDB\with_transaction($session, $callback);
} catch (MongoDB\Driver\Exception\RuntimeException $e) {
echo 'Caught exception: ', $e->getMessage(), PHP_EOL;
}
Successfully performed transaction!
Summary: SAVINGS +1000 CHECKING -1000

Note

Parallel Operations Not Supported

The PHP library does not support running parallel operations within a single transaction.

To learn more about the concepts mentioned in this guide, see the following pages in the MongoDB Server manual:

To learn more about ACID compliance, see the What are ACID Properties in Database Management Systems? article on the MongoDB website.

To learn more about insert operations, see the Insert Documents guide.

To learn more about the methods and types mentioned in this guide, see the following API documentation:

To learn more about the Session class and methods, see the following PHP extension API documentation:

Back

Bulk Write Operations

On this page