0
0
MongoDBquery~5 mins

Change streams on databases in MongoDB

Choose your learning style9 modes available
Introduction
Change streams let you watch for changes in your database in real time. This helps you react quickly when data updates happen.
You want to update a user interface immediately when data changes.
You need to keep multiple systems in sync when database data changes.
You want to log or audit changes happening in your database.
You want to trigger actions automatically after certain data updates.
You want to monitor database activity without constantly asking for data.
Syntax
MongoDB
const changeStream = db.watch(pipeline, options);
The 'db.watch()' method starts watching changes on the whole database.
You can use 'pipeline' to filter which changes you want to see.
Examples
Watch all changes on the database without filters.
MongoDB
const changeStream = db.watch();
Watch only insert operations on the database.
MongoDB
const changeStream = db.watch([{ $match: { operationType: 'insert' } }]);
Watch all changes and get the full updated document after changes.
MongoDB
const changeStream = db.watch([], { fullDocument: 'updateLookup' });
Sample Program
This code watches for new documents inserted anywhere in the database. When a new document is added, it prints the document details.
MongoDB
const changeStream = db.watch([{ $match: { operationType: 'insert' } }]);
changeStream.on('change', (change) => {
  print('New document inserted:', JSON.stringify(change.fullDocument));
});
OutputSuccess
Important Notes
Change streams require a replica set or a sharded cluster in MongoDB.
You can watch changes on a single collection, a database, or the whole cluster.
Remember to close the change stream when you no longer need it to save resources.
Summary
Change streams let you listen to real-time changes in your database.
Use 'db.watch()' to start watching changes with optional filters.
They help keep apps and systems updated instantly when data changes.