Transactions and Streams

Transactions and Change Streams

Both features here require a replica set; a standalone mongod refuses them, because both are built on the oplog and the majority-commit machinery only a replica set has. Multi-document transactions change several documents in several collections as one unit that either lands completely or not at all. Change streams let you subscribe to those committed changes as they happen, rather than polling.

They are halves of one mechanism. A write reserves a snapshot in WiredTiger, applies its changes there, and at commit writes one oplog entry per operation and makes the snapshot visible. Replication and change streams both read that oplog — which is why a change stream never shows a change that was rolled back, and why a resume token stops working once the oplog scrolls past it. Every listing below ran against a single-node replica set:

A single-node replica set for development
mongod --port 28108 --dbpath /tmp/rs-data --replSet rs0
mongosh "mongodb://127.0.0.1:28108/test?directConnection=true" --eval "rs.initiate()"

rs.initiate() answers { info2: 'no configuration specified. Using a default configuration for the set', ok: 1 } and the member elects itself primary in a second or two. Production uses three; see Replica Sets and Elections and Read Preference.

A transaction's changes reach readers and change streams only after commit
A transaction's changes reach readers and change streams only after commit

Subsections