Problem Statement
What do Change Streams in MongoDB allow applications to do?
Explanation
Change Streams allow applications to listen for real-time changes to data in collections, databases, or entire clusters. They provide a way to build event-driven architectures by capturing insert, update, replace, and delete operations as they occur.
Change Streams use the oplog as their source and are available on replica sets and sharded clusters. They are useful for triggering actions based on data changes, maintaining caches, replicating data to other systems, or building real-time features.
Code Solution
SolutionRead Only
// Watch for changes on a collection
const changeStream = db.collection('orders').watch()
changeStream.on('change', (change) => {
console.log('Change detected:', change)
if (change.operationType === 'insert') {
// Handle new order
notifyWarehouse(change.fullDocument)
} else if (change.operationType === 'update') {
// Handle order update
updateInventory(change.documentKey._id)
}
})
// Watch with filter
const pipeline = [
{ $match: { 'fullDocument.status': 'completed' } }
]
db.orders.watch(pipeline)