Change Streams allow applications to listen to real-time data changes across a collection, database, or entire deployment without polling the database.
1. How Change Streams Work
Change Streams read directly from the MongoDB oplog (Operations Log) in a replica set. Whenever an insert, update, replace, or delete occurs, MongoDB pushes an event notification to active listeners.
2. Building a Real-Time Order Notification Service
const orderCollection = db.collection("orders");
// Listen for new orders with total > $500
const changeStream = orderCollection.watch([
{
$match: {
operationType: "insert",
"fullDocument.total": { $gte: 500 }
}
}
]);
changeStream.on("change", (changeEvent) => {
const newOrder = changeEvent.fullDocument;
console.log(`High-value order received: ${newOrder.order_number} for $${newOrder.total}`);
// Trigger WebSocket push notification to admin dashboard
webSocketServer.broadcast({
type: "VIP_ORDER_ALERT",
payload: newOrder
});
});