How to Watch Collection Changes in MongoDB
To watch collection changes in MongoDB, use the
watch() method on a collection to open a change stream. This stream provides real-time notifications of inserts, updates, deletes, and other operations on the collection.Syntax
The watch() method is called on a MongoDB collection to start listening for changes. It returns a change stream cursor that you can iterate or listen to for events.
collection.watch(pipeline, options)pipeline: Optional aggregation pipeline to filter or transform change events.options: Optional settings likefullDocumentto get the full updated document.
javascript
const changeStream = collection.watch(pipeline, options);Example
This example shows how to watch changes on a collection and log each change event in real time.
javascript
const { MongoClient } = require('mongodb'); async function watchCollection() { const uri = 'mongodb://localhost:27017'; const client = new MongoClient(uri); try { await client.connect(); const db = client.db('testdb'); const collection = db.collection('testcollection'); const changeStream = collection.watch(); console.log('Watching for changes...'); changeStream.on('change', (change) => { console.log('Change detected:', change); }); // Keep the process alive to listen await new Promise(() => {}); } finally { // client.close(); // Uncomment to close connection when done } } watchCollection().catch(console.error);
Output
Watching for changes...
Change detected: { _id: ..., operationType: 'insert', fullDocument: {...}, ns: {...}, documentKey: {...} }
Change detected: { _id: ..., operationType: 'update', updateDescription: {...}, ... }
Common Pitfalls
- Not keeping the process alive: The change stream listens asynchronously, so the program must stay running to receive events.
- Not handling errors: Always add error handling on the change stream to catch disconnections.
- Using an unsupported MongoDB version: Change streams require MongoDB 3.6 or later.
- Not specifying
fullDocumentoption when you want the updated document in update events.
javascript
/* Wrong: Not keeping process alive, so no events received */ const changeStream = collection.watch(); changeStream.on('change', (change) => { console.log(change); }); // Program exits immediately /* Right: Keep process alive with a promise or loop */ await new Promise(() => {});
Quick Reference
| Method | Description |
|---|---|
| collection.watch() | Starts watching changes on the collection |
| changeStream.on('change', callback) | Listens for change events |
| pipeline | Optional filter to watch specific changes |
| options.fullDocument | Returns the full updated document on update events |
Key Takeaways
Use collection.watch() to open a change stream for real-time updates.
Keep your program running to continuously receive change events.
Specify options like fullDocument to get detailed update info.
Handle errors and disconnections on the change stream.
Change streams require MongoDB version 3.6 or newer.