- Reference >
mongo
Shell Methods >- Connection Methods >
- Session >
- Session.commitTransaction()
Session.commitTransaction()¶
On this page
Definition¶
-
Session.
commitTransaction
()¶ New in version 4.0: Transactions are available for replica sets.
Saves the changes made by the operations in the multi-document transaction and ends the transaction. Until the commit, none of the data changes made from within the transaction are visible outside the transaction.
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.
Retryable¶
If the commit operation encounters an error, MongoDB drivers retry the
commit operation a single time regardless of whether
retryWrites
is set to true
. For more information, see
Transactions in Applications.
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.