0
0
MongoDBquery~30 mins

Change streams on collections in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Monitor Real-Time Changes with MongoDB Change Streams
📖 Scenario: You are building a simple inventory system for a small store. You want to watch for any changes in the products collection so you can update your dashboard in real-time whenever a product is added, updated, or deleted.
🎯 Goal: Create a MongoDB change stream on the products collection to listen for all changes and print the change events.
📋 What You'll Learn
Create a MongoDB collection named products with some sample documents.
Set up a change stream on the products collection.
Listen for all change events (insert, update, delete).
Print the change event documents as they occur.
💡 Why This Matters
🌍 Real World
Change streams help applications react instantly to database changes, like updating dashboards, syncing data, or triggering alerts.
💼 Career
Understanding change streams is useful for backend developers, database administrators, and anyone building real-time data-driven applications.
Progress0 / 4 steps
1
Create the products collection with sample data
Create a MongoDB collection called products and insert these exact documents: { _id: 1, name: "Apple", quantity: 50 }, { _id: 2, name: "Banana", quantity: 30 }, and { _id: 3, name: "Orange", quantity: 20 }.
MongoDB
Need a hint?

Use db.products.insertMany([...]) to add multiple documents at once.

2
Create a change stream cursor on the products collection
Create a variable called changeStream that opens a change stream on the products collection using db.products.watch().
MongoDB
Need a hint?

Use const changeStream = db.products.watch() to start watching changes.

3
Listen for change events using the change stream cursor
Use a while loop with await changeStream.hasNext() and inside the loop assign const change = await changeStream.next() to get each change event.
MongoDB
Need a hint?

Use while (await changeStream.hasNext()) to wait for changes and const change = await changeStream.next() to get each event.

4
Print each change event inside the loop
Inside the while loop, add printjson(change) to display the change event document.
MongoDB
Need a hint?

Use printjson(change) to nicely print the change event document.