Skip to content

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 } })
Bad — transaction around one document; and a race dressed as safety
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 abort
Better — operators for one doc; txn only when two docs must commit together

Transactions 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.