Common Mistakes
Unnecessary Transactions
Wrapping a single-document update in a transaction, and the latency you pay for it.
IntermediateAbout 4 minutes
Problem. A repository opens a session for every updateOne 'for ACID'. Or the opposite: find-then-$set stock with no filter and no $inc.
await session.withTransaction(async () => {
await users.updateOne({ name: "Rahul" }, { $set: { city: "Pune" } }, { session })
})
const p = await products.findOne({ name: "Mechanical Keyboard" })
await products.updateOne({ _id: p._id }, { $set: { stock: p.stock - 1 } })await users.updateOne({ name: "Rahul" }, { $set: { city: "Pune" } })
await products.updateOne(
{ name: "Mechanical Keyboard", stock: { $gte: 1 } },
{ $inc: { stock: -1 } }
)
// txn: insert order + $inc stock, or abortTransactions cost snapshot, locks, and ~60s max. They do not fix a check-then-act you left outside the session. If every write is a txn, embed more or you copied SQL.
Interview question
When is a MongoDB transaction the wrong tool?
Think about it first.
When a single-document update already gives atomicity — $inc stock with a stock filter, $set on one user. Wrapping that in a session costs throughput and does not make find-then-set safe. I use a transaction when two documents must commit together.