0
0
MongoDBquery~5 mins

Use cases for change streams 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 live dashboard when new data arrives.
You need to sync data changes from one database to another automatically.
You want to send notifications when important data changes.
You want to audit or log all changes happening in your database.
You want to trigger other processes when data is inserted, updated, or deleted.
Syntax
MongoDB
const changeStream = collection.watch(pipeline, options);
The 'pipeline' lets you filter which changes to watch.
The 'options' can control things like full document retrieval.
Examples
Watch all changes on the collection without filters.
MongoDB
const changeStream = collection.watch();
Watch only insert operations.
MongoDB
const changeStream = collection.watch([{ $match: { operationType: 'insert' }}]);
Get the full updated document on update events.
MongoDB
const changeStream = collection.watch([], { fullDocument: 'updateLookup' });
Sample Program
This program watches the 'orders' collection for new inserts. When a new order is added, it prints the order details.
MongoDB
const { MongoClient } = require('mongodb');

async function watchInserts() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('shop');
  const collection = db.collection('orders');

  const changeStream = collection.watch([{ $match: { operationType: 'insert' } }]);

  console.log('Watching for new orders...');
  changeStream.on('change', (change) => {
    console.log('New order inserted:', change.fullDocument);
  });
}

watchInserts();
OutputSuccess
Important Notes
Change streams require a replica set or sharded cluster in MongoDB.
They provide real-time notifications without polling the database.
You can filter changes to reduce noise and focus on relevant events.
Summary
Change streams help you react instantly to database changes.
Use them for live updates, syncing, notifications, and auditing.
You can filter and customize what changes to watch.