0
0
MongoDBquery~30 mins

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

Choose your learning style9 modes available
Monitor Database Changes with MongoDB Change Streams
📖 Scenario: You are managing a MongoDB database for an online bookstore. You want to track any changes made to the books collection in real-time to update your inventory system promptly.
🎯 Goal: Build a MongoDB change stream that listens to changes on the books collection and captures insert, update, and delete events.
📋 What You'll Learn
Create a MongoDB collection named books with sample documents.
Define a change stream on the books collection.
Configure the change stream to listen for insert, update, and delete operations.
Implement the change stream to print the change events.
💡 Why This Matters
🌍 Real World
Change streams help applications react instantly to database changes, such as updating user interfaces or syncing data across services.
💼 Career
Understanding change streams is valuable for backend developers and database administrators who build real-time data-driven applications.
Progress0 / 4 steps
1
Create the books collection with sample data
Create a MongoDB collection called books and insert these exact documents: { _id: 1, title: "The Hobbit", author: "J.R.R. Tolkien" } and { _id: 2, title: "1984", author: "George Orwell" }.
MongoDB
Need a hint?

Use db.books.insertMany() with an array of documents.

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

Use db.books.watch() to create the change stream cursor.

3
Configure the change stream to filter for insert, update, and delete events
Modify the changeStream to watch only for insert, update, and delete operation types by passing a pipeline with $match to db.books.watch().
MongoDB
Need a hint?

Pass a pipeline array with { $match: { operationType: { $in: [...] } } } to db.books.watch().

4
Listen for change events and print them
Use changeStream.on('change', callback) to listen for change events and print each event using console.log(change) inside the callback function.
MongoDB
Need a hint?

Use changeStream.on('change', (change) => { console.log(change) }) to listen and print events.