Pretty printing and cursor behavior in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When working with MongoDB queries, it's important to understand how the way results are shown and handled affects performance.
We want to know how the time to get and display data changes as the amount of data grows.
Analyze the time complexity of the following MongoDB query with pretty printing and cursor usage.
const cursor = db.collection.find({ status: "active" });
cursor.pretty();
while (cursor.hasNext()) {
printjson(cursor.next());
}
This code finds all documents with status "active", formats them nicely, and prints each one.
Look for repeated actions that affect time.
- Primary operation: Iterating over each document in the cursor to print it.
- How many times: Once for every matching document in the collection.
As the number of matching documents grows, the time to print each one grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The time grows directly with the number of documents to print.
Time Complexity: O(n)
This means the time to print all documents grows in a straight line with the number of documents.
[X] Wrong: "Pretty printing or using a cursor makes the query faster or slower by itself."
[OK] Correct: Pretty printing only changes how results look, not how many documents are processed. The cursor just helps fetch documents one by one, so time depends on how many documents match.
Understanding how data retrieval and display scale helps you explain performance clearly and shows you know how databases handle results efficiently.
"What if we used a limit to only fetch 10 documents? How would that change the time complexity?"
Practice
pretty() method do when used after a MongoDB query?Solution
Step 1: Understand the purpose of
Thepretty()pretty()method formats the output of a query to make it easier to read by adding indentation and line breaks.Step 2: Compare with other options
Limiting, sorting, or deleting documents are done by other methods likelimit(),sort(), orremove(), notpretty().Final Answer:
Formats the output to be more readable with indentation and line breaks -> Option AQuick Check:
pretty()improves readability [OK]
- Confusing pretty() with limit() or sort()
- Thinking pretty() changes the data
- Assuming pretty() affects query results count
Solution
Step 1: Recall cursor methods in MongoDB
The correct method to check if a cursor has more documents ishasNext().Step 2: Verify other options
Methods likehasMore(),nextExists(), ormore()do not exist in MongoDB cursor API.Final Answer:
cursor.hasNext() -> Option BQuick Check:
Use hasNext() to check cursor availability [OK]
- Using non-existent cursor methods
- Confusing hasNext() with next()
- Assuming hasNext() returns the document itself
var cursor = db.users.find({age: {$gt: 25}}).pretty();
while(cursor.hasNext()) {
printjson(cursor.next());
}Solution
Step 1: Analyze the query and cursor usage
The query finds users with age > 25 and applies pretty() to format output. The while loop uses hasNext() and next() to print each document.Step 2: Understand the output behavior
Each matching document is printed in readable JSON format until no documents remain.Final Answer:
All user documents with age greater than 25 printed in readable JSON format -> Option CQuick Check:
Cursor iterates all matching docs with pretty print [OK]
- Thinking pretty() breaks chaining
- Assuming only one document prints
- Forgetting to call next() as a function
var cursor = db.products.find().pretty();
if(cursor.hasNext) {
printjson(cursor.next());
}
What is the problem with this code?Solution
Step 1: Identify method usage errors
The methodhasNextis used without parentheses, so it refers to the function itself, not its boolean result.Step 2: Understand impact on code behavior
BecausehasNextis not called, the if condition always evaluates to true (function exists), causing unexpected behavior.Final Answer:
hasNext is used without parentheses, so it does not check correctly -> Option AQuick Check:
Always call hasNext() with parentheses [OK]
- Using hasNext without parentheses
- Thinking pretty() causes error
- Calling next() before checking hasNext()
orders collection where status is "shipped" in a readable format, but only 3 at a time to avoid memory overload. Which code snippet correctly achieves this?Solution
Step 1: Limit query results to 3 documents
Usinglimit(3)restricts the cursor to only 3 documents matching the filter.Step 2: Use pretty() to format output and iterate with hasNext()/next()
Chainingpretty()formats output. The while loop prints each document until the 3 limited documents are exhausted.Final Answer:
var cursor = db.orders.find({status: "shipped"}).limit(3).pretty(); while(cursor.hasNext()) { printjson(cursor.next()); } -> Option DQuick Check:
limit(3) + pretty() + hasNext()/next() prints 3 formatted docs [OK]
- Not using limit() to restrict documents
- Calling pretty() after iteration instead of chaining
- Incorrect loop control causing infinite or missing output
