MongoDB Multi-Document Transactions

Execute atomic multi-document operations across collections with sessions.

In MongoDB, operations on a single document are atomic. For operations across multiple documents or collections, MongoDB supports distributed ACID transactions within a client session.

Key Takeaways: MongoDB Multi-Document Transactions

Mastering MongoDB Multi-Document Transactions helps you write clean and reliable MongoDB code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

MongoDB Multi-Document Transactions Code Example

MongoDB
const session = db.getMongo().startSession();
session.startTransaction();
try {
  session.getDatabase("store").orders.insertOne({ id: 1, total: 100 });
  session.getDatabase("store").inventory.updateOne({ id: "item1" }, { $inc: { stock: -1 } });
  session.commitTransaction();
} catch (e) {
  session.abortTransaction();
}
Output
Atomically completes order creation and stock deduction
Run this example on your own computer. The "Get Started" lesson shows how to set it up.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services