- Reference >
mongo
Shell Methods >- Connection Methods >
- Session >
- Session.commitTransaction()
Session.commitTransaction()¶
On this page
Definition¶
-
Session.
commitTransaction
()¶ New in version 4.0.
Saves the changes made by the operations in the multi-document transaction and ends the transaction.
Availability
- In version 4.0, MongoDB supports multi-document transactions on replica sets.
- In version 4.2, MongoDB introduces distributed transactions, which adds support for multi-document transactions on sharded clusters and incorporates the existing support for multi-document transactions on replica sets.
Behavior¶
Write Concern¶
When commiting the transaction, the session uses the write concern
specified at the transaction start. See
Session.startTransaction()
.
If you commit using "w: 1"
write concern,
your transaction can be rolled back during the failover process.
Atomicity¶
When a transaction commits, all data changes made in the transaction are saved and visible outside the transaction. That is, a transaction will not commit some of its changes while rolling back others.
Until a transaction commits, the data changes made in the transaction are not visible outside the transaction.
However, when a transaction writes to multiple shards, not all
outside read operations need to wait for the result of the committed
transaction to be visible across the shards. For example, if a
transaction is committed and write 1 is visible on shard A but write
2 is not yet visible on shard B, an outside read at read concern
"local"
can read the results of write 1 without
seeing write 2.
Retryable¶
If the commit operation encounters an error, MongoDB drivers retry the
commit operation a single time regardless of whether
retryWrites
is set to false
. For more information, see
Transaction Error Handling.
Example¶
Consider a scenario where as changes are made to an employee’s record
in the hr
database, you want to ensure that the events
collection in the reporting
database are in sync with the hr
changes. That is, you want to ensure that these writes are done as a
single transaction, such that either both operations succeed or fail.
The employees
collection in the hr
database has the following
documents:
The events
collection in the reporting
database has the
following documents:
The following example opens a transaction, updates an employee’s status
to Inactive
in the employees
status and inserts a corresponding
document to the events
collection, and commits the two operations
as a single transaction.