MongoDB Change Streams

MongoDB Change Streams

Jaya
December 1st, 2026
25
07:00 Minutes

Imagine you run an e-commerce website. When a customer places an order, your application needs to update inventory, send a confirmation email and notify the warehouse.

MongoDB Change Streams make this possible by allowing applications to detect real-time database changes without repeatedly querying the database. They provide structured events for inserts, updates, deletions and replacements at the collection, database, or deployment level.

In this guide, we will explore how MongoDB Change Streams work, how to implement them and how they help build real-time applications.

Also Explore: Indexing in MongoDB

What Are MongoDB Change Streams?

MongoDB Change Streams allow your application to listen for real-time data changes, such as new records, updates, deletions and replacements. They work at the collection, database, or entire deployment level. Instead of repeatedly checking the database for changes or manually reading the oplog, your application can receive change events as they happen.

MongoDB uses its replication system, called the oplog, to track these changes and send structured events once they have been confirmed by a majority of the replica set members. For more details, refer to the MongoDB Change Streams manual.

How Do MongoDB Change Streams Work?

MongoDB Change Streams use the database's replication system to detect and deliver changes in real time. The process works in five simple steps:

How Do MongoDB Change Streams Work?

Application: The application inserts, updates, or deletes a document in MongoDB.

  1. MongoDB: MongoDB processes the database operation and records it in the oplog.
  2. Oplog: The oplog stores the changes made to the database.
  3. Change Stream: MongoDB converts the recorded changes into structured change events.
  4. Application or downstream service: The application receives these events and performs actions such as updating inventory, sending notifications, or synchronizing data with another system.

As shown in the image, MongoDB Change Streams connect database changes with applications and downstream services which allows them to respond without repeatedly checking the database for updates.

Also Read: How to Create a Collection in MongoDB?

What Are the Requirements for Using MongoDB Change Streams?

Before implementing Change Streams, you need to make sure your MongoDB deployment meets the necessary requirements.

RequirementExplanation
Replica set or sharded clusterChange Streams are not supported on standalone MongoDB deployments.
WiredTiger storage engineThe deployment must use the WiredTiger storage engine.
Replica set protocol version 1The replica set or sharded cluster must use pv1.
Appropriate permissionsThe application needs the find and changeStream privileges for the resources it watches.
Supported MongoDB driverUse a MongoDB driver that supports Change Streams and the required server features.

Change Streams are available in MongoDB replica sets and sharded clusters. For a replica set, you can open a stream from any data-bearing member. For a sharded cluster, you must open it through a mongos instance.

Can you use Change Streams with MongoDB Atlas?

Yes, MongoDB Atlas supports Change Streams on supported cluster deployments.

However, a standalone local MongoDB server is not sufficient. If you are testing Change Streams locally, configure a replica set.

For production applications, also check the deployment's MongoDB version, driver compatibility, access permissions and connection settings before implementing the feature.

Types of MongoDB Change Streams

MongoDB lets you watch changes at three different levels. The right choice depends on how much data your application needs to monitor.


1. Collection-level Change Streams

A collection-level Change Stream monitors a single collection.

For example, an e-commerce application can watch the orders collection to receive notifications whenever an order is inserted, updated, or deleted.

This is useful when an application has a specific responsibility, such as processing new orders or monitoring customer records.

2. Database-level Change Streams

A database-level Change Stream monitors changes across all non-system collections in a database.

For example, an application can watch the e-commerce database to monitor changes in its orders, customers and products collections.

This approach is useful when a service needs to track changes across multiple collections without opening a separate stream for each one.

3. Deployment-level Change Streams

A deployment-level Change Stream monitors changes across all non-system collections in the databases included in a MongoDB deployment.

For example, a centralized monitoring service may need to track changes across several databases.

Deployment-level streams are useful for broad monitoring and integration tasks. However, they can generate more events than a collection-level stream, so filtering and resource planning become especially important.

MongoDB supports all three monitoring levels through its Change Stream APIs.

Read Also: How to Get MongoDB Certification: A Complete Guide

Understanding MongoDB Change Stream Events

Whenever a watched resource changes, MongoDB returns a structured change event document.

The event contains information about what happened, where it happened and which document was affected.

Here is a simplified example of an insert event:

{
"operationType": "insert",
"fullDocument": {
"_id": 101,
"product": "Laptop",
"quantity": 1
},
"ns": {
"db": "ecommerce",
"coll": "orders"
},
"documentKey": {
"_id": 101
}
}

This event tells the application that a new document was inserted into the orders collection in the ecommerce database.

The actual event also includes fields such as _id, which contains a resume token and clusterTime, which identifies the operation's logical time.

Common operation types

Operation typeWhat it means
insertA new document was added.
updateAn existing document was modified.
replaceAn existing document was replaced.
deleteA document was removed.
dropA collection was dropped.
renameA collection was renamed.
dropDatabaseA database was dropped.
invalidateThe change stream was invalidated, such as after a collection drop or rename.

MongoDB also supports expanded events for certain operations, including collection and index changes. These require the showExpandedEvents option and are available from MongoDB 6.0.

What does fullDocument mean?

For insert events, MongoDB includes the inserted document in fullDocument.

For update events, the default behavior is different. MongoDB returns an updateDescription that identifies the fields that changed, rather than automatically returning the entire updated document.

For example:

{
"operationType": "update",
"updateDescription": {
"updatedFields": {
"status": "shipped"
},
"removedFields": [],
"truncatedArrays": []
}
}

If your application needs the current version of the entire document, you can configure the stream with fullDocument: "updateLookup".

Keep in mind that this lookup returns the most current majority-committed version of the document at the time of the lookup. It may not represent the exact document state immediately after the original update if other writes have occurred in between.

Also Explore: Data Types in MongoDB

How to Implement MongoDB Change Streams

You can implement Change Streams using MongoDB drivers in languages such as JavaScript, Python, Java and C#.

The following example uses the official MongoDB Node.js driver.

Step 1: Connect to MongoDB

First, make sure you have Node.js, the MongoDB Node.js driver and access to a replica set or supported sharded cluster.

Install the driver using npm:

npm install mongodb

Step 2: Open a Change Stream

Create a JavaScript file named change-stream.js and add the following code:

const { MongoClient } = require("mongodb");
async function main() {
const client = new MongoClient(
"YOUR_MONGODB_CONNECTION_STRING"
);
try {
await client.connect();
const database = client.db("ecommerce");
const orders = database.collection("orders");
const changeStream = orders.watch();
console.log("Listening for order changes...");
for await (const change of changeStream) {
console.log("Change detected:", change);
}
} finally {
await client.close();
}
}
main().catch(console.error);

This example opens a Change Stream on the orders collection and listens for incoming events.

The watch() method creates the stream, while the for await...of loop reads change events as they arrive.

The official Node.js driver supports this asynchronous iteration approach.

Step 3: Filter the events you need

Suppose your application only needs to process newly inserted orders.

You can filter the stream to listen only for insert events:

const changeStream = orders.watch([
{
$match: {
operationType: "insert"
}
}
]);

Now, the stream will deliver insert events that match the filter.

This is useful when an application needs to process a specific type of change without handling every update or deletion.

You can also filter events based on fields such as the database name, collection name, or document key.

Step 4: Process the change event

You can use the event to trigger another task.

For example:

for await (const change of changeStream) {
if (change.operationType === "insert") {
console.log(
"New order:",
change.fullDocument
);
}
}

In a real application, you could use this event to send an order confirmation, update a search index, or notify another service.

The event processing logic should be designed carefully. If the application crashes after receiving an event but before completing the task, it may need to process that event again after restarting.

Step 5: Close the stream when it is no longer needed

Change Streams keep a cursor open while they wait for new events.

When your application no longer needs the stream, close it to release the associated resources.

For example, in a long-running application, you can close the stream during shutdown or when a service is being stopped.

The driver provides a close() method for this purpose.

Also Explore: How to Install MongoDB on Windows?

Common Use Cases for MongoDB Change Streams

Change Streams are useful whenever an application needs to respond to database changes without repeatedly checking for them.

1. Real-time notifications

A messaging application can watch its messages collection. When a new message is inserted, the application can notify the recipient.

This helps create a more responsive experience without requiring continuous database polling.

2. E-commerce order processing

An e-commerce application can watch its orders collection and respond when a new order is created.

The event can trigger inventory updates, warehouse notifications, or order confirmation emails.

3. Synchronizing data between systems

Suppose a business stores customer information in MongoDB but also maintains a separate search index.

A Change Stream can notify the synchronization service when customer records change. The service can then update the search index.

This helps keep data consistent across systems without requiring a complete database scan each time.

4. Real-time dashboards

A dashboard can use Change Streams to monitor changes in sales, inventory, or customer activity.

When a relevant event occurs, the application can update the displayed information.

5. Data integration and ETL

Change Streams can support Extract, Transform and Load (ETL) processes by notifying downstream systems about new or modified data.

For example, a data pipeline can receive change events and use them to update a reporting database or analytics platform.

MongoDB identifies ETL services, cross-platform synchronization, collaboration features and notification services as common Change Stream use cases.

Also Explore: MongoDB vs MySQL: Understanding Key Differences

MongoDB Change Streams vs. Polling

Polling is a method in which an application repeatedly queries a database to check whether something has changed.

Change Streams allow the application to receive change events as they occur.

FeatureMongoDB Change StreamsPolling
How it worksListens for database changesRepeatedly queries the database
Response timeCan deliver events as changes occurDepends on the polling interval
Database queriesAvoids repeated queries just to detect changesRequires repeated queries
Resource usageUses an open stream and server resourcesUses resources for each query
ImplementationRequires a supported MongoDB deploymentCan work with a basic database connection
Best suited forReal-time or near-real-time applicationsSimple periodic checks

For example, if an application checks the database every 30 seconds, it may take up to 30 seconds to detect a new record, depending on when the record is created.

A Change Stream can deliver a notification without waiting for the next polling cycle.

However, Change Streams are not automatically the best option for every application. If you only need to check for changes once every few hours, a simple polling process may be easier to maintain.

Also Read: MongoDB Tutorial

MongoDB Change Streams vs. Triggers and Change Data Capture

Change Streams, database triggers and Change Data Capture (CDC) all help applications respond to data changes, but they work in different ways.

Change Streams vs. database triggers

Database triggers are configured to run an action when a database event occurs.

MongoDB Change Streams provide a stream of change events that an application can consume and process.

For example, a Change Stream can notify an external service when a document is updated. A trigger-based system may execute a predefined action in response to a database operation.

The key difference is that Change Streams provide an event stream, while triggers are designed to execute actions based on database events.

Change Streams vs. Change Data Capture

Change Data Capture is a broader approach to tracking database changes and sending them to other systems.

MongoDB Change Streams are one way to implement CDC for MongoDB data.

For example, an application can use Change Streams to capture updates from MongoDB and send them to a reporting system, message broker, or another database.

FeatureChange StreamsDatabase triggersCDC
Primary purposeStream database changesExecute actions after database eventsCapture and distribute data changes
Main mechanismMongoDB change event notificationsTrigger-based executionDepends on the CDC implementation
Typical useReal-time applications and integrationsDatabase-level automationData pipelines and system synchronization

Change Streams are particularly useful when you need an application to respond to changes without building a custom process to read the oplog directly.

Benefits of MongoDB Change Streams

MongoDB Change Streams offer several advantages for applications that need to monitor data changes.

  • Real-time notifications: Applications can receive change events as they occur instead of waiting for the next polling cycle.
  • Simpler implementation: Developers can use MongoDB's built-in Change Stream APIs instead of manually reading the oplog.
  • Flexible monitoring: Streams can monitor a collection, database, or deployment.
  • Event filtering: Aggregation pipelines can filter and transform events before the application processes them.
  • Reliable change tracking: Change Streams notify applications about majority-committed changes.
  • Integration support: They can help connect MongoDB with messaging systems, analytics platforms, search indexes and other services.

These benefits make Change Streams a useful option for applications that depend on timely updates and reliable event processing.

Read Also: A Comprehensive Guide to Data Modeling in MongoDB

Limitations of MongoDB Change Streams

Although Change Streams are useful, they have some limitations that developers should understand before using them in production.

1. They require a supported deployment

Change Streams are not available on standalone MongoDB deployments. You need a replica set or sharded cluster with the required configuration.

2. They depend on oplog history

MongoDB uses oplog information to generate change events and resume streams.

If an application is offline for too long and the required operation is no longer available in the oplog, it may not be able to resume from its saved resume token.

3. They consume database resources

Each active Change Stream holds a connection open while waiting for new events.

If the number of active streams exceeds the connection pool size, notification latency can increase. This makes connection pool sizing important when many streams are active.

4. Event processing requires careful design

Applications need to handle failures, retries and duplicate processing carefully.

For example, if an application receives an event and then crashes before completing its task, the event may need to be processed again.

5. They do not replace every messaging system

Change Streams can notify applications about database changes, but they do not automatically provide every feature of a dedicated messaging system.

If your application requires advanced message routing, long-term event retention, or complex stream processing, you may need additional infrastructure.

How to Resume MongoDB Change Streams After an Interruption

One of the most useful features of MongoDB Change Streams is the ability to resume a stream after an interruption.

Each change event contains a resume token in its _id field.

The application can save this token and use it to resume the stream later.

For example, suppose an application receives an event and stores its resume token. If the connection is interrupted, the application can use that token to continue reading changes.

MongoDB provides two important options:

OptionPurpose
resumeAfterResumes notifications after the operation identified by the token.
startAfterStarts a new stream after the operation identified by the token, including after an invalidate event.

The difference matters when a collection is dropped or renamed. In such cases, the stream may be invalidated and startAfter is the appropriate option for starting a new stream after the invalidate event.

Example of resuming a Change Stream

const changeStream = orders.watch();
changeStream.on("change", (change) => {
const resumeToken = change._id;
// Save the resume token
// so the application can resume later.
});

In a production application, save the token in durable storage rather than keeping it only in memory.

The application should also make sure that the token is saved in a way that matches its event-processing strategy. For example, if an event is processed but its token is not saved, the application may receive the event again after restarting.

What happens if the resume token is no longer valid?

MongoDB needs the relevant oplog history to resume a Change Stream.

If the operation associated with the resume token has already been removed from the oplog, MongoDB cannot resume the stream from that token.

In this situation, the application may need to perform a fresh data synchronization or recovery process before opening a new stream.

Read Also: MongoDB vs PostgreSQL

Best Practices for MongoDB Change Streams

To use Change Streams effectively in production, follow these best practices.

1. Watch only the data you need

Use collection-level streams when possible. If you only need to monitor orders, there is no reason to process changes across the entire deployment.

2. Filter events early

Use an aggregation pipeline to filter events before they reach your application.

This reduces unnecessary event processing and can make the application easier to maintain.

3. Save resume tokens reliably

Store resume tokens in durable storage so your application can resume after a restart or interruption.

Make sure your event-processing logic and token-saving logic work together to avoid losing events or processing them incorrectly.

4. Design for retries and duplicate events

A stream may resume after a failure and an application may process an event more than once.

Use idempotent processing where possible. This means processing the same event multiple times should not create incorrect results.

5. Monitor connection pool capacity

Each active stream uses a connection while waiting for new events.

If your application opens many streams, make sure the connection pool is large enough to support them without introducing unnecessary latency.

6. Plan for oplog retention

Your application should not rely on being able to resume indefinitely from an old token.

Monitor the oplog window and design a recovery process for cases where a saved token is no longer usable.

7. Close unused streams

Close streams when they are no longer required. This helps release resources and prevents unnecessary active connections.

8. Test failure scenarios

Before deploying a Change Stream-based application, test what happens when the database connection drops, the application restarts, or event processing fails.

A well-designed recovery process is just as important as receiving the initial change event.

Key Takeaways

MongoDB Change Streams allow applications to listen for real-time database changes without repeatedly querying MongoDB or manually reading the oplog.

They are useful for notifications, order processing, data synchronization, real-time dashboards and other applications that need to respond to database changes.

Before using them, make sure your deployment meets the requirements and that your application can handle interruptions, retries and resume tokens.

For production applications, focus on filtering events, managing connections, saving resume tokens and designing reliable event-processing logic.

The bottom line: MongoDB Change Streams provide a practical way to build responsive applications that react to database changes as they happen.

About the Author
Jaya | igmGuru
About the Author

Jaya is a big data professional with experience building large-scale data pipelines and helping teams move from spreadsheet reporting to distributed systems such as Hadoop and Spark. Jaya's expertise includes data engineering, schema management, and cluster performance tuning. She has been working with us for a long time and loves to write well-researched content pieces for our learners.

Drop Us a Query
Fields marked * are mandatory
Recent Post
×

Your Shopping Cart


Your shopping cart is empty.