0
0
MongoDBquery~5 mins

Change stream events (insert, update, delete) in MongoDB

Choose your learning style9 modes available
Introduction

Change streams let you watch for changes in your database in real time. You can see when data is added, changed, or removed.

You want to update a live dashboard when new data is added.
You need to send notifications when someone changes their profile.
You want to keep another system in sync with your database changes.
You want to log all changes for auditing purposes.
Syntax
MongoDB
const changeStream = collection.watch();
changeStream.on('change', (change) => {
  // handle change event
});
Use collection.watch() to start watching changes on a collection.
The change event object tells you what type of change happened.
Examples
This listens for new documents added to the collection and prints them.
MongoDB
const changeStream = collection.watch();
changeStream.on('change', (change) => {
  if (change.operationType === 'insert') {
    console.log('New document inserted:', change.fullDocument);
  }
});
This listens for updates and shows which document changed.
MongoDB
const changeStream = collection.watch();
changeStream.on('change', (change) => {
  if (change.operationType === 'update') {
    console.log('Document updated:', change.documentKey);
  }
});
This listens for deletions and shows which document was removed.
MongoDB
const changeStream = collection.watch();
changeStream.on('change', (change) => {
  if (change.operationType === 'delete') {
    console.log('Document deleted:', change.documentKey);
  }
});
Sample Program

This program connects to a MongoDB database, watches the 'items' collection for insert, update, and delete events, and prints details about each change.

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

async function watchChanges() {
  const client = new MongoClient('mongodb://localhost:27017');
  await client.connect();
  const db = client.db('testdb');
  const collection = db.collection('items');

  const changeStream = collection.watch();
  console.log('Watching for changes...');

  changeStream.on('change', (change) => {
    switch (change.operationType) {
      case 'insert':
        console.log('Insert event:', change.fullDocument);
        break;
      case 'update':
        console.log('Update event on document:', change.documentKey);
        break;
      case 'delete':
        console.log('Delete event on document:', change.documentKey);
        break;
      default:
        console.log('Other event:', change);
    }
  });
}

watchChanges();
OutputSuccess
Important Notes

Change streams require a replica set or sharded cluster in MongoDB.

The change object contains different fields depending on the event type.

You can filter change streams to watch only certain events or documents.

Summary

Change streams let you listen to insert, update, and delete events in real time.

Use collection.watch() and listen for the change event.

Each event tells you what changed and gives details about the change.