Change streams are MongoDB’s first-party answer to “tell me when something in this collection changes”. They are an oplog tailing engine wrapped in an aggregation pipeline and exposed as a cursor — server-side filtering, resumability across primary failovers, and the same $match/$project vocabulary your application code already uses. This article shows how to build a consumer that does not lose events when the application crashes, the primary fails over, or the database rolls back a write.
How to verify
Open a change stream from mongosh and inspect a single event:
mongosh --host primary.example.internal:27017
use shop
const cs = db.orders.watch([], { fullDocument: "updateLookup" })
cs.next()
db.orders.insertOne({ sku: "X-100", qty: 1 })
cs.next()
db.serverStatus().opcounters
The cursor blocks until an event arrives. Each event carries an _id (the resume token), an operationType, the namespace, the document key, and — if fullDocument: "updateLookup" was requested — a snapshot of the post-image of the document.
What’s happening
A change stream is server-side syntactic sugar over the oplog (the operation log every replica-set primary writes to its local database). When you call db.coll.watch(), the server opens a tailable cursor over the oplog filtered to your namespace, applies any aggregation pipeline you provided, and returns events one at a time. Because events are oplog-driven, change streams require a replica-set (single-node mongod with replSetName set is enough) and inherit the durability properties of writeConcern: "majority" — every event you read has been replicated to a majority of voters.
Resume tokens are the crash-safety mechanism. Every event includes an opaque token; if your consumer dies and restarts, pass the last successfully-processed token as resumeAfter (or startAfter) and the stream picks up exactly where you left off — even across primary failovers, because the token encodes the cluster time and the operation’s position in the oplog. The catch: the oplog is a capped collection. If your consumer is offline longer than the oplog window, the token becomes invalid and you must replay from a snapshot.
Pre-image and post-image lookup let you see the document state. fullDocument: "updateLookup" issues a findOne for the current state at event-read time — which means by the time you read it, another update may already have happened. fullDocumentBeforeChange: "required" returns the pre-image but requires changeStreamPreAndPostImages: true on the collection — set at createCollection or collMod time, with the storage cost paid by the database.
The procedure
-
Enable pre/post-images on the collection if you need them. This is the only way to get a “before” snapshot of an update.
db.runCommand({ collMod: "orders", changeStreamPreAndPostImages: { enabled: true } }) -
Decide on filtering at the pipeline level, not in the consumer. Filtering server-side keeps the consumer thin and avoids paying for events you discard.
const pipeline = [ { $match: { operationType: { $in: ["insert", "update", "replace"] } } }, { $match: { "fullDocument.status": { $in: ["paid", "fulfilled"] } } } ] -
Open the cursor with the right document lookup options.
const cs = db.orders.watch(pipeline, { fullDocument: "updateLookup", fullDocumentBeforeChange: "whenAvailable", batchSize: 100, maxAwaitTimeMS: 2000 }) -
Persist the resume token after every successful processing step. Store it in a checkpoint document in the same cluster — that way the checkpoint participates in the same durability and backup as the source.
while (cs.hasNext()) { const ev = cs.next() try { handle(ev) db.checkpoints.updateOne( { _id: "orders-consumer" }, { $set: { token: ev._id, at: new Date() } }, { upsert: true }) } catch (e) { backoff(e); break; } } -
On restart, resume from the saved token. Use
startAfterif you want to resume past an invalidate event (a drop or rename),resumeAfterotherwise.const last = db.checkpoints.findOne({ _id: "orders-consumer" }) const cs = db.orders.watch(pipeline, { fullDocument: "updateLookup", startAfter: last.token }) -
Watch the cluster instead of a collection when you need to fan out across many namespaces.
db.getMongo().watch()opens a deployment-wide stream — useful for general-purpose CDC pipelines feeding /en/knowledge-base/kafka-connect-source-sink/.
Operational notes
- Oplog sizing dictates how long a consumer can be offline. Default oplog is 5% of disk up to 50 GB. For long-running CDC consumers, size it for the maximum tolerable outage window —
replSetResizeOplogadjusts it without a restart. invalidateevents end the cursor. A collection drop, database drop, or rename emits an invalidate and closes the stream. Catch it explicitly and decide whether to resume against the new namespace or stop.- Sharded clusters add ordering caveats. Cross-shard ordering of events is by cluster time, not insertion order — events on different shards are interleaved by the
mongosmerge. If strict per-document order is required, watch by document key or pre-shard the consumer. writeConcern: "majority"-aware reads only. Change stream events are visible only after majority commit. Writes acknowledged with weaker write concern can show up later — or roll back and never appear.- Backpressure must be handled by the consumer. A slow consumer holds the cursor open and consumes oplog window; instrument lag (
oplog windowminustime since last processed token) and alert before the window runs out.
Stack Harbor builds change-stream consumers as part of the operating model for MongoDB-backed applications — feeding search indexes, audit logs, downstream caches, and analytics warehouses. We size the oplog window against the slowest credible consumer outage, run checkpoint-tail-lag dashboards, and handle the resume-vs-start-from-snapshot decision when an outage exceeds the window. See /en/services/managed-operations/ for how this fits into the broader engagement.