Change streams are a powerful feature in MongoDB that allow you to listen for and respond to changes in real-time as they occur in your collections. This makes them ideal for applications that require near-instantaneous updates, such as real-time analytics, live dashboards, or event-driven architectures.
A change stream is a cursor that provides a continuous flow of documents describing the changes to a collection. These changes can be inserts, updates, deletes, and more. You can use change streams to monitor data modifications and react accordingly.
To use change streams, you need to have MongoDB 3.6 or later installed. You can enable change streams on any replica set or sharded cluster.
Here's a basic example of how to set up a change stream using the MongoDB Node.js driver:
const { MongoClient } = require('mongodb');
async function run() {
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('your_collection_name');
const changeStream = collection.watch();
changeStream.on('change', (next) => {
console.log(next);
});
} finally {
await client.close();
}
}
run().catch(console.dir);
collection.watch() to create a change stream.change event is emitted whenever there's a change in the monitored collection.You can filter change events using the match option in the watch method. This allows you to specify criteria for which changes should be included in the stream.
const changeStream = collection.watch([
{ $match: { "operationType": "insert" } }
]);
changeStream.on('change', (next) => {
console.log("New document inserted:", next.fullDocument);
});
insert, update, delete, etc.).When a change event is detected, you can handle it in various ways depending on your application's requirements.
changeStream.on('change', (next) => {
switch (next.operationType) {
case 'insert':
console.log("Inserted:", next.fullDocument);
break;
case 'update':
console.log("Updated:", next.updateDescription.updatedFields);
break;
case 'delete':
console.log("Deleted document with _id:", next.documentKey._id);
break;
}
});
resumeToken to ensure your application can resume from where it left off after a restart or failure.let resumeToken;
async function run() {
const uri = "your_mongodb_connection_string";
const client = new MongoClient(uri);
try {
await client.connect();
const database = client.db('your_database_name');
const collection = database.collection('your_collection_name');
let changeStream;
if (resumeToken) {
changeStream = collection.watch([], { resumeAfter: resumeToken });
} else {
changeStream = collection.watch();
}
changeStream.on('change', (next) => {
console.log(next);
resumeToken = next._id; // Update the resume token
});
await new Promise(resolve => setTimeout(resolve, 60000)); // Run for 1 minute
} finally {
await client.close();
}
}
run().catch(console.dir);
_id field of each change event.Change streams are a powerful feature in MongoDB that enable real-time data processing and monitoring. By understanding how to set up, filter, and handle change events, you can build applications that respond quickly to data changes. Always consider best practices for error handling, resumability, performance, and security to ensure your application is robust and efficient.
This tutorial provides a comprehensive guide to using change streams in MongoDB, covering everything from basic setup to advanced filtering and handling techniques.