0
0
MongoDBquery~5 mins

Change streams on collections in MongoDB

Choose your learning style9 modes available
Introduction
Change streams let you watch for changes in a collection so you can react to them right away without checking the data again and again.
You want to update a user interface immediately when data changes.
You need to keep data in sync between different parts of your app.
You want to log or audit changes made to your data.
You want to trigger actions when specific data changes happen.
You want to build real-time notifications based on database updates.
Syntax
MongoDB
const changeStream = db.collection('yourCollection').watch(pipeline, options);
The 'pipeline' is optional and lets you filter which changes to watch.
The 'options' can control things like full document return or resume tokens.
Examples
Watch all changes on the 'orders' collection.
MongoDB
const changeStream = db.collection('orders').watch();
Watch only insert operations on the 'orders' collection.
MongoDB
const pipeline = [ { $match: { operationType: 'insert' } } ];
const changeStream = db.collection('orders').watch(pipeline);
Watch all changes and get the full updated document after update operations.
MongoDB
const changeStream = db.collection('orders').watch([], { fullDocument: 'updateLookup' });
Sample Program
This code listens for any change on the 'products' collection and prints the change details as they happen.
MongoDB
const changeStream = db.collection('products').watch();
changeStream.on('change', (change) => {
  printjson(change);
});
OutputSuccess
Important Notes
Change streams require a replica set or sharded cluster; they do not work on standalone MongoDB servers.
You can use change streams to build reactive apps that respond instantly to data changes.
Remember to close the change stream when you no longer need it to free resources.
Summary
Change streams let you watch for real-time changes in a collection.
You can filter which changes to watch using a pipeline.
Use change streams to build live updates, notifications, or audit logs.