0
0
MongoDBquery~30 mins

Change stream events (insert, update, delete) in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Track Product Inventory Changes with MongoDB Change Streams
📖 Scenario: You manage a small store's product inventory using MongoDB. You want to watch for any changes to the products collection so you can react when products are added, updated, or removed.
🎯 Goal: Create a MongoDB change stream to listen for insert, update, and delete events on the products collection.
📋 What You'll Learn
Create a products collection with initial product documents.
Define a change stream pipeline to filter for insert, update, and delete events.
Open the change stream on the products collection using the pipeline.
Add a listener to handle and log the change events.
💡 Why This Matters
🌍 Real World
Change streams help businesses monitor live changes in their databases, such as inventory updates or user activity, enabling real-time reactions.
💼 Career
Understanding change streams is valuable for roles like database administrators, backend developers, and data engineers who build reactive and event-driven applications.
Progress0 / 4 steps
1
Create the products collection with initial data
Create a products collection and insert these exact documents: { _id: 1, name: "Pen", quantity: 100 }, { _id: 2, name: "Notebook", quantity: 200 }, and { _id: 3, name: "Eraser", quantity: 150 }.
MongoDB
Need a hint?

Use db.products.insertMany() with an array of product objects.

2
Define a change stream pipeline to filter events
Create a variable called pipeline that filters change events to only include insert, update, and delete operations using { $match: { operationType: { $in: ["insert", "update", "delete"] } } }.
MongoDB
Need a hint?

Use const pipeline = [{ $match: { operationType: { $in: ["insert", "update", "delete"] } } }].

3
Open the change stream on the products collection
Create a variable called changeStream that opens a change stream on db.products using the pipeline variable.
MongoDB
Need a hint?

Use const changeStream = db.products.watch(pipeline) to open the change stream.

4
Add a listener to handle and log change events
Use changeStream.on("change", (change) => { ... }) to add a listener that logs the change object to the console.
MongoDB
Need a hint?

Use changeStream.on("change", (change) => { console.log("Change detected:", change) }).