What is Change Stream in MongoDB: Explained with Examples
change stream in MongoDB is a feature that lets applications listen to real-time changes in the database collections or entire deployment. It provides a continuous feed of data changes like inserts, updates, and deletes without needing to poll the database.How It Works
Imagine you have a live news feed that updates instantly whenever something new happens. MongoDB's change stream works similarly by providing a live feed of changes happening in your database. Instead of checking the database repeatedly, your application can just listen to this feed and react immediately.
Under the hood, MongoDB uses its internal replication mechanism to track changes and expose them through a stream. When you open a change stream on a collection or database, MongoDB sends you events like document inserts, updates, deletes, or even schema changes as they happen.
This makes it easy to build real-time features like notifications, syncing data between services, or auditing changes without complex polling or manual tracking.
Example
This example shows how to open a change stream on a MongoDB collection using the Node.js driver. It listens for new inserts and prints the changed document.
const { MongoClient } = require('mongodb'); async function watchChanges() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('testdb'); const collection = db.collection('testcollection'); const changeStream = collection.watch(); console.log('Watching for changes...'); changeStream.on('change', (change) => { if (change.operationType === 'insert') { console.log('New document inserted:', change.fullDocument); } }); } catch (err) { console.error(err); } } watchChanges();
When to Use
Use change streams when you want your application to respond instantly to database changes without delay. Common use cases include:
- Real-time notifications: Alert users immediately when new data arrives.
- Data synchronization: Keep caches or other databases updated automatically.
- Audit logging: Track who changed what and when in your data.
- Event-driven architectures: Trigger workflows or microservices based on data changes.
Change streams are especially useful in modern apps that require live updates, like chat apps, dashboards, or collaborative tools.
Key Points
- Change streams provide a real-time feed of database changes.
- They work by listening to MongoDB's internal replication events.
- You can watch changes on a collection, database, or entire deployment.
- They help build reactive, event-driven applications easily.
- Requires MongoDB replica set or sharded cluster to work.