- Reference >
mongoShell Methods >- Connection Methods >
- Session >
- Session.abortTransaction()
Session.abortTransaction()¶
On this page
Definition¶
-
Session.abortTransaction()¶ 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.
Important
mongoShell MethodThis page documents a
mongomethod. This is not the documentation for database commands or language-specific drivers, such as Node.js. To use the database command, see theabortTransactioncommand.For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.
Changed in version 4.2: Starting in MongoDB 4.2, multi-document transactions are available for both sharded clusters and 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.