0
0
MongoDBquery~5 mins

Why change streams are needed in MongoDB

Choose your learning style9 modes available
Introduction
Change streams let you watch for changes in your database in real time without constantly checking it yourself.
You want to update a live dashboard when data changes.
You need to send notifications when new data is added.
You want to keep two databases in sync automatically.
You want to trigger actions right after data updates.
You want to audit or log changes as they happen.
Syntax
MongoDB
const changeStream = collection.watch(pipeline, options);
You call watch() on a collection, database, or the whole cluster.
The pipeline lets you filter which changes to listen for.
Examples
Watch all changes on the 'orders' collection.
MongoDB
const changeStream = db.collection('orders').watch();
Watch only new documents inserted into 'orders'.
MongoDB
const pipeline = [{$match: {'operationType': 'insert'}}];
const changeStream = db.collection('orders').watch(pipeline);
Sample Program
This listens for any change in the 'products' collection and prints details when a change happens.
MongoDB
const changeStream = db.collection('products').watch();
changeStream.on('change', (change) => {
  console.log('Change detected:', JSON.stringify(change));
});
OutputSuccess
Important Notes
Change streams use MongoDB's internal replication to provide real-time updates efficiently.
They avoid the need for slow and repeated queries to check for changes.
You can filter and transform change events using aggregation pipelines.
Summary
Change streams help you react instantly to database changes.
They are useful for live updates, notifications, syncing, and auditing.
You set them up with watch() and can filter events with pipelines.