What are change streams in MongoDB?
Answer
Change streams allow applications to access real-time data changes in MongoDB collections, databases, or entire deployments without the complexity of tailing the oplog. Introduced in MongoDB 3.6, they provide a higher-level, resumable, filtered stream of change events. Opening a change stream: const changeStream = db.orders.watch(); changeStream.on("change", (change) => { console.log(change); });. Change event structure: each event includes: _id (resume token — allows resuming from a specific point after reconnection), operationType (insert/update/delete/replace/drop/rename), fullDocument (the affected document), updateDescription (what fields changed for update operations), ns (namespace: database + collection). Filtering: pass an aggregation pipeline to filter events: db.orders.watch([{ $match: { operationType: "insert" } }]). Resuming: store the last processed _id (resume token); on reconnect: db.orders.watch([], { resumeAfter: lastToken }) — continues from where you left off. Requirements: change streams require a replica set or sharded cluster (not standalone). Use cases: real-time notifications, syncing data to cache/search index, event-driven microservices (trigger workflow on data change), audit logging, replicating data to other systems (CDC). Fullness: the fullDocument: "updateLookup" option returns the full document after an update (not just the changed fields) — note this is slightly stale if concurrent updates occur.