Do Transactions Exist in MongoDB? — Interview Answer — MongoDB Technical Interview Questions & Answers

Model answer covering multi-document ACID transactions.

Do Transactions Exist in MongoDB? — Interview Answer

  • Model answer: One document is always atomic. Multi-document transactions exist on replica sets for things like transferring marks between two docs.
  • I would not wrap every insert in a transaction.

Technical Interview Tip: Atomic document vs multi-doc transaction.

Code Examples for Do Transactions Exist in MongoDB? — Interview Answer

Do Transactions Exist in MongoDB? — Interview Answer — working example

// mongosh / driver-style multi-document transaction (replica set / mongos required)
session = db.getMongo().startSession()
session.startTransaction()
try {
  const users = session.getDatabase("prep_pilot").users
  const accounts = session.getDatabase("prep_pilot").accounts
  users.updateOne({ email: "ada@example.com" }, { $inc: { points: -10 } })
  accounts.updateOne({ email: "ada@example.com" }, { $inc: { balance: 10 } })
  session.commitTransaction()
} catch (e) {
  session.abortTransaction()
  throw e
} finally {
  session.endSession()
}

Do Transactions Exist in MongoDB? — Interview Answer — multi-document ACID transactions need a replica set (or sharded cluster) and a session.

How to Explain Do Transactions Exist in MongoDB? — Interview Answer to an Interviewer

Does Mongo have transactions?

Yes, multi-document on replica sets Single doc already atomic