Transactions and consistency
Group changes that must all succeed or all fail, and choose how durable a write must be.
- Explain why a replica set is needed for transactions.
- Open a session with startSession and commit work with withTransaction.
- Choose a write concern such as majority for durability.
- Describe what read concern controls.
In plain English
A replica set is several MongoDB servers keeping the same data so the system keeps working if one fails. A session, opened with startSession, is a way to run commands that belong together. withTransaction wraps a block of work so that either every change commits or none of them do. A write concern says how many copies must acknowledge a write before it is reported as successful, and a read concern says which state of the data you are willing to read. Multi-document transactions only work on a replica set, so a single standalone server cannot run them.
Step by step
- 1Confirm you are connected to a replica set rather than a standalone server.
- 2Open a session with db.getMongo().startSession().
- 3Run several updates inside session.withTransaction.
- 4Close the session with endSession when you are done.
- 5Set writeConcern to majority for writes that must survive a crash.
const session = db.getMongo().startSession()
session.withTransaction(async () => {
const accounts = session.getDatabase("bank").accounts
await accounts.updateOne(
{ _id: "ada" },
{ $inc: { balance: -100 } }
)
await accounts.updateOne(
{ _id: "grace" },
{ $inc: { balance: 100 } }
)
})
session.endSession()
db.accounts.updateOne(
{ _id: "ada" },
{ $inc: { balance: -10 } },
{ writeConcern: { w: "majority" } }
)Common mistakes
- Running a multi-document transaction against a standalone server fails because transactions require a replica set.
- Doing slow network or human work inside a transaction holds locks and blocks other operations.
- Assuming a write is safely stored just because it was acknowledged, without setting a stronger write concern, is unsafe.
- Ending a session without committing or aborting the transaction leaves the session hanging in an uncertain state.
Move money atomically
Open a session and transfer 50 from account "ada" to account "grace" inside withTransaction so both updates commit or neither does.
const session = db.getMongo().startSession()What does a write concern of "majority" guarantee?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.