Bird
Raised Fist0
MongoDBquery~20 mins

Change streams on databases in MongoDB - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Change Stream Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Output of a simple change stream watching a database
Consider a MongoDB change stream opened on a database watching all collections. If a document is inserted into a collection, what does the change stream event's operationType field show?
MongoDB
const changeStream = db.watch();
// Insert a document into any collection
// What is the value of operationType in the change event?
A"replace"
B"insert"
C"update"
D"delete"
Attempts:
2 left
💡 Hint
Think about what operation happens when a new document is added.
🧠 Conceptual
intermediate
1:30remaining
Understanding resume tokens in change streams
What is the purpose of a resume token in MongoDB change streams?
ATo limit the number of events returned in a batch
BTo filter change events by operation type
CTo uniquely identify the last seen event so the stream can resume from there
DTo encrypt the change stream data for security
Attempts:
2 left
💡 Hint
Think about how you can continue watching changes after a disconnection.
📝 Syntax
advanced
2:30remaining
Correct syntax to watch changes on a database with a filter
Which of the following MongoDB commands correctly opens a change stream on a database filtering only insert operations?
MongoDB
const pipeline = [ { $match: { operationType: "insert" } } ];
const changeStream = db.watch(pipeline);
Aconst changeStream = db.watch([{ $match: { operationType: "insert" } }]);
Bconst changeStream = db.watch([{ $filter: { operationType: "insert" } }]);
Cconst changeStream = db.watch([{ match: { operationType: "insert" } }]);
Dconst changeStream = db.watch({ $match: { operationType: "insert" } });
Attempts:
2 left
💡 Hint
Remember the aggregation pipeline syntax uses $match inside an array.
🔧 Debug
advanced
3:00remaining
Why does this change stream not receive any events?
A developer runs this code to watch changes on a database but never receives any events, even after inserting documents: const changeStream = db.watch([{ $match: { operationType: "insert" } }]); changeStream.on('change', (next) => console.log(next)); What is the most likely reason?
AThe change stream is opened on the database, but the insertions happen in a different database
BThe $match stage is incorrectly filtering out all events
CThe changeStream.on event listener is not set up correctly
DThe MongoDB server does not support change streams on databases
Attempts:
2 left
💡 Hint
Check if the watched database matches where inserts happen.
❓ optimization
expert
3:30remaining
Optimizing change stream pipeline for minimal data transfer
You want to watch changes on a database but only need the document key (_id) and operationType fields in the change events to reduce network usage. Which pipeline optimizes the change stream to return only these fields?
A[ { $project: { documentKey: 0, operationType: 1 } } ]
B[ { $match: { operationType: { $exists: true } } }, { $project: { _id: 0 } } ]
C[ { $project: { fullDocument: 0 } } ]
D[ { $project: { 'documentKey._id': 1, operationType: 1, _id: 0 } } ]
Attempts:
2 left
💡 Hint
Use $project to include only needed fields and exclude the default _id.

Practice

(1/5)
1. What is the main purpose of MongoDB change streams on databases?
easy
A. To listen for real-time changes in the database
B. To backup the database automatically
C. To create indexes on collections
D. To run queries faster

Solution

  1. Step 1: Understand what change streams do

    Change streams allow applications to watch for changes like inserts, updates, or deletes in real-time.
  2. Step 2: Compare options with this purpose

    Only To listen for real-time changes in the database describes listening to real-time changes, which matches the main purpose of change streams.
  3. Final Answer:

    To listen for real-time changes in the database -> Option A
  4. Quick Check:

    Change streams = real-time listening [OK]
Hint: Change streams = real-time database updates listener [OK]
Common Mistakes:
  • Confusing change streams with backups
  • Thinking change streams create indexes
  • Assuming change streams speed up queries
2. Which of the following is the correct syntax to start watching changes on a MongoDB database named mydb?
easy
A. watch.db('mydb')
B. db.watch('mydb')
C. db.mydb.watch()
D. db.getSiblingDB('mydb').watch()

Solution

  1. Step 1: Recall how to access a database in MongoDB shell

    To access a database other than the current one, use db.getSiblingDB('mydb').
  2. Step 2: Apply the watch() method on the database object

    The watch() method is called on the database object to start change streams.
  3. Final Answer:

    db.getSiblingDB('mydb').watch() -> Option D
  4. Quick Check:

    Use getSiblingDB to access db, then watch() [OK]
Hint: Use db.getSiblingDB('name').watch() to watch a database [OK]
Common Mistakes:
  • Trying to call watch() directly on db with database name
  • Using incorrect method like db.watch('name')
  • Confusing method order or syntax
3. Given the following code snippet, what will be the output if a document is inserted into any collection in the testdb database?
const changeStream = db.getSiblingDB('testdb').watch();
changeStream.forEach((change) => {
  printjson(change.operationType);
});
medium
A. "update"
B. "delete"
C. "insert"
D. No output

Solution

  1. Step 1: Understand what triggers the change event

    The change stream listens to all changes in the database, including inserts, updates, and deletes.
  2. Step 2: Identify the operationType for an insert

    When a document is inserted, the operationType is "insert".
  3. Final Answer:

    "insert" -> Option C
  4. Quick Check:

    Insert triggers operationType = "insert" [OK]
Hint: Insert triggers operationType 'insert' in change stream [OK]
Common Mistakes:
  • Expecting 'update' or 'delete' for insert events
  • Thinking no output occurs without filters
  • Confusing event names with method names
4. Identify the error in this code snippet that tries to watch changes on the sales database:
const changeStream = db.sales.watch();
changeStream.forEach((change) => {
  printjson(change);
});
medium
A. The watch() method cannot be called on a database object
B. The database should be accessed using getSiblingDB('sales') before calling watch()
C. The on() method is not valid for change streams
D. Missing parentheses after watch

Solution

  1. Step 1: Check how the database is accessed

    Using db.sales accesses a collection named 'sales' in the current database, not the database itself.
  2. Step 2: Correct way to access a different database

    To watch changes on the 'sales' database, use db.getSiblingDB('sales').watch().
  3. Final Answer:

    The database should be accessed using getSiblingDB('sales') before calling watch() -> Option B
  4. Quick Check:

    Use getSiblingDB to access database, not db.sales [OK]
Hint: Use getSiblingDB('name') to access database, not db.name [OK]
Common Mistakes:
  • Assuming db.sales is a database instead of a collection
  • Thinking watch() can't be called on database objects
  • Confusing event handling methods
5. You want to watch only update operations on the orders database using change streams. Which code snippet correctly applies a filter to achieve this?
hard
A. db.getSiblingDB('orders').watch([{ $match: { operationType: 'update' } }])
B. db.orders.watch({ operationType: 'update' })
C. db.getSiblingDB('orders').watch({ filter: { operationType: 'update' } })
D. db.getSiblingDB('orders').watch([{ $filter: { operationType: 'update' } }])

Solution

  1. Step 1: Recall how to filter change streams

    Change streams accept an aggregation pipeline array to filter events, using stages like $match.
  2. Step 2: Apply correct syntax for filtering updates

    The correct filter is [{ $match: { operationType: 'update' } }] passed as an array to watch().
  3. Final Answer:

    db.getSiblingDB('orders').watch([{ $match: { operationType: 'update' } }]) -> Option A
  4. Quick Check:

    Use $match in array to filter change streams [OK]
Hint: Use watch([{ $match: { operationType: 'update' } }]) to filter updates [OK]
Common Mistakes:
  • Passing filter as object instead of pipeline array
  • Using invalid keys like 'filter' or '$filter'
  • Calling watch() on collection instead of database
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard