5 min read
•Question 19 of 27hardWhat are Change Streams in MongoDB?
Real-time data change notifications.
What You'll Learn
- What change streams are
- Setting up watchers
- Use cases
What are Change Streams?
Change streams allow applications to watch for real-time changes in collections, databases, or deployments.
Basic Usage
code.jsJavaScript
const changeStream = db.collection('orders').watch();
changeStream.on('change', (change) => {
console.log('Change detected:', change);
});
// With async iterator
for await (const change of changeStream) {
console.log(change);
}Change Event Structure
code.jsJavaScript
{
_id: { ... }, // Resume token
operationType: 'insert', // insert, update, delete, replace
fullDocument: { ... }, // The document (for insert/update)
ns: { db: 'mydb', coll: 'orders' },
documentKey: { _id: ObjectId('...') },
updateDescription: { // For updates
updatedFields: { status: 'shipped' },
removedFields: []
}
}Filtering Changes
code.jsJavaScript
const pipeline = [
{ $match: { operationType: { $in: ['insert', 'update'] } } },
{ $match: { 'fullDocument.status': 'completed' } }
];
const changeStream = collection.watch(pipeline);With Mongoose
code.jsJavaScript
const Order = mongoose.model('Order', orderSchema);
Order.watch().on('change', (change) => {
if (change.operationType === 'insert') {
sendNotification(change.fullDocument);
}
});Resume After Disconnect
code.jsJavaScript
let resumeToken;
changeStream.on('change', (change) => {
resumeToken = change._id;
// Process change
});
// Later, resume from token
const newStream = collection.watch([], { resumeAfter: resumeToken });Use Cases
- Real-time notifications
- Data synchronization
- Audit logging
- Cache invalidation