On this page本页内容
Session.
abortTransaction
()¶New in version 4.0.版本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
When a transaction aborts, all data changes made by the writes in the transaction are discarded without ever becoming visible and the transaction ends.
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.
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.