0
0
MongoDBquery~5 mins

Watch method for real-time updates in MongoDB

Choose your learning style9 modes available
Introduction

The watch method lets you see changes in your database as they happen. It helps you react quickly without checking over and over.

You want to update a chat app instantly when someone sends a message.
You need to refresh a dashboard when new data arrives.
You want to notify users immediately when their order status changes.
You want to keep multiple users' views in sync in real time.
You want to log changes as soon as they happen for auditing.
Syntax
MongoDB
const changeStream = collection.watch(pipeline, options);
changeStream.on('change', (change) => {
  // handle change event
});

collection.watch() starts watching changes on a collection.

You can add a pipeline to filter which changes to watch.

Examples
Watch all changes in the 'messages' collection and print them.
MongoDB
const changeStream = db.collection('messages').watch();
changeStream.on('change', (change) => {
  console.log('Change detected:', change);
});
Watch only new inserts in the 'orders' collection.
MongoDB
const pipeline = [
  { $match: { operationType: 'insert' } }
];
const changeStream = db.collection('orders').watch(pipeline);
changeStream.on('change', (change) => {
  console.log('New order:', change.fullDocument);
});
Sample Program

This program connects to a MongoDB database called 'shop' and watches the 'orders' collection for new orders. When a new order is added, it prints the order details immediately.

MongoDB
const { MongoClient } = require('mongodb');

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

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

  console.log('Watching for new orders...');

  changeStream.on('change', (change) => {
    console.log('New order received:', change.fullDocument);
  });
}

watchOrders();
OutputSuccess
Important Notes

The watch method requires MongoDB replica sets or sharded clusters.

Remember to close the change stream when done to avoid resource leaks.

You can watch at database or cluster level too, not just collections.

Summary

The watch method helps you get real-time updates from your database.

You can filter which changes to watch using a pipeline.

It is useful for apps that need instant reactions to data changes.