This program connects to a MongoDB database, watches the 'items' collection for insert, update, and delete events, and prints details about each change.
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();