乐闻世界logo
搜索文章和话题

How to achieve rollback in transactions in mongoDB?

1个答案

1

In MongoDB, transactions are typically used in environments supporting multi-document ACID transactions, such as MongoDB 4.0 and above in replica sets or MongoDB 4.2 and above in sharded clusters. Transactions help ensure data consistency and integrity. MongoDB supports transaction rollback to handle errors or exceptions that occur during transaction execution.

Steps to Implement Transaction Rollback

  1. Start Transaction: Use MongoDB's client session (client.startSession()) to initiate a new session and employ session.startTransaction() to begin a transaction.

    javascript
    const session = client.startSession(); session.startTransaction();
  2. Execute Operations: Perform the required database operations within the transaction context. These operations must utilize the same session instance to guarantee execution within the transaction scope.

    javascript
    try { const collection = client.db("mydatabase").collection("mycollection"); await collection.insertOne({ item: "apple", qty: 100 }, { session }); await collection.insertOne({ item: "orange", qty: 150 }, { session });
  3. Commit or Rollback Transaction: Decide to commit or rollback the transaction based on operation outcomes. Commit if all operations succeed; rollback if any operation fails to maintain data consistency.

    javascript
    await session.commitTransaction(); console.log("Transaction committed."); } catch (error) { await session.abortTransaction(); console.log("Transaction aborted due to an error: ", error); } finally { session.endSession(); }

Example Scenario

Suppose you are managing a database for an e-commerce platform. You need to update inventory information and record transaction logs. First, attempt to insert new inventory entries and log entries within a transaction. If an error occurs during insertion (e.g., network issues or data conflicts), roll back these changes to prevent data inconsistency.

By following these steps, MongoDB enables developers to leverage transactions in database operations for maintaining data integrity and consistency. Transaction rollback is a critical mechanism to restore consistency when issues arise.

2024年6月29日 12:07 回复

你的答案