- Reference >
mongo
Shell Methods >- Connection Methods >
- Session >
- Session.abortTransaction()
Session.abortTransaction()¶
On this page
Definition¶
-
Session.
abortTransaction
()¶ New in version 4.0.
Terminates the multi-document transaction and rolls back any data changes made by the operations within the transaction. That is, the transaction ends without saving any of the changes made by the operations in 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¶
Atomicity¶
When a transaction aborts, all data changes made by the writes in the transaction are discarded without ever becoming visible and the transaction ends.
Retryable¶
If the abort operation encounters an error, MongoDB drivers retry the
abort operation a single time regardless of whether
retryWrites
is set to true
. 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 and vice versa. 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 employees
collection has a unique index on the employee
field:
The events
collection in the reporting
database has the
following documents:
The following example opens a transaction, attempts to add a record to
the events
collection and add a document to the employees
collection. If the operation encounters an error in either operations
or in committing the transaction, the session aborts the transaction.