MongoDB doesn’t use traditional locking or complex transaction with Rollback. MongoDB is designed to be light weighted, fast and predictable to its performance. It keeps transaction support simple to enhance performance.
MongoDB supports multi-document transactions starting from version 4.0. With multi-document transactions, you can perform multiple operations on one or more documents within a single transaction. This ensures the consistency of your data, and the changes made during the transaction are either all committed or all rolled back.
Here is a basic outline of how transactions work in MongoDB:
- Start a Session:
- To perform transactions, you need to start a session using
startSession()
.
const session = db.getMongo().startSession();
- To perform transactions, you need to start a session using
- Start a Transaction:
- Begin a transaction within the session using
startTransaction()
.
session.startTransaction();
- Begin a transaction within the session using
- Perform Operations:
- Execute your read and write operations as part of the transaction. Use the session when executing the operations.
session.withTransaction(() => {
// Perform operations using the session
});
- Commit the Transaction:
- If all operations are successful and you want to commit the changes, use
commitTransaction()
.
session.commitTransaction();
- If all operations are successful and you want to commit the changes, use
- Rollback the Transaction:
- If an error occurs or you decide to discard the changes, use
abortTransaction()
.
session.abortTransaction();
- If an error occurs or you decide to discard the changes, use
Note that transactions in MongoDB have some limitations and considerations. They are only supported on replica sets and require the WiredTiger storage engine. Additionally, long-running transactions may have performance implications.
It’s essential to carefully design your schema and choose appropriate indexes to minimize the need for transactions. While transactions are a powerful tool, it’s also important to understand when and how to use them effectively in your application.
For more detailed information and examples, you should refer to the official MongoDB documentation, as features and best practices may evolve with newer versions: