What is a change stream in MongoDB?

IntermediateConceptMongoDB
Answer

Short answer

A change stream lets applications subscribe to real-time changes (inserts, updates, deletes) on a collection, database or whole cluster, using the replica set's oplog under the hood. It's used for event-driven systems, cache invalidation, syncing to search indexes and audit trails.

Example

const stream = db.orders.watch([{ $match: { operationType: "insert" } }]);
while (stream.hasNext()) {
  const change = stream.next();
  print(`New order: ${change.fullDocument._id}`);
}

In app code (Node.js):

const stream = client.db("shop").collection("orders").watch();
stream.on("change", (event) => publishToKafka(event));

Requirements and tips

  • Needs a replica set or sharded cluster.
  • Store the resume token so the consumer can continue after a restart without missing events.
  • The resume token must still be inside the oplog window.
  • Alternative for pipelines: Debezium / Kafka Connect MongoDB connector.

What to say in the interview

"Change streams expose real-time inserts, updates and deletes from the oplog for event-driven processing, such as syncing to Elasticsearch or Kafka. Consumers persist resume tokens, and the oplog window must cover consumer downtime."

All Databases (MySQL, PostgreSQL, MongoDB) questions Roadmap: MongoDB basics

More on MongoDB