Working with Change Streams

1. Opening Change Stream

ScopeCommand
Collectiondb.coll.watch(pipeline, opts)
Databasedb.watch()
Clusterclient.watch()

2. Filtering Change Events

StageDetail
$matchFirst stage; filter by operationType, ns, fullDocument fields
$projectReshape change events
db.orders.watch([{ $match: { operationType: { $in: ["insert","update"] } } }]);

3. Understanding Change Event Structure

FieldDetail
_idResume token
operationTypeinsert|update|replace|delete|drop|rename|invalidate
fullDocumentCurrent doc (with option)
updateDescriptionupdatedFields, removedFields, truncatedArrays
clusterTimeLogical timestamp
ns{db, coll}

4. Resuming Change Stream

OptionDetail
resumeAfterFrom a known token
startAfterPast invalidate events
AutoDrivers auto-resume on transient errors

5. Using Full Document Option

ValueEffect
defaultupdateDescription only
updateLookupLatest doc snapshot
whenAvailable / requiredWith pre/post images

6. Using Full Document Before Change

AspectDetail
RequirescollMod with changeStreamPreAndPostImages: { enabled: true }
OptionfullDocumentBeforeChange: "whenAvailable" | "required"

7. Watching Specific Operations

FilterExample
Inserts{operationType:"insert"}
By field{"fullDocument.status":"PAID"}
By update path{"updateDescription.updatedFields.price":{$exists:true}}

8. Setting Start Time

OptionDetail
startAtOperationTimeBegin at given clusterTime (within oplog window)

9. Handling Change Stream Errors

ScenarioAction
TransientDriver auto-retries with last token
InvalidateStream closes; use startAfter to resume
Token expiredRestart with startAtOperationTime

10. Using Change Streams with Aggregation

StageDetail
$match, $project, $addFields, $replaceRoot, $redactSupported
$lookup, $group, $out, $mergeNot supported in change pipelines

11. Monitoring Database/Collection Changes

Watch TargetVisibility
CollectionSingle namespace
DatabaseAll collections in DB
DeploymentAll non-system DBs (mongos/replSet)