Challenge - 5 Problems
Pretty Printing and Cursor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate2:00remaining
Output of find() with pretty()
What is the output of the following MongoDB query on a collection with documents {"name": "Alice", "age": 30} and {"name": "Bob", "age": 25}?
MongoDB
db.users.find().pretty()
Attempts:
2 left
💡 Hint
pretty() formats the output with indentation and line breaks.
✗ Incorrect
The pretty() method formats the cursor output to be more readable by adding line breaks and indentation, showing each document on its own lines but not as a JSON array.
🧠 Conceptual
intermediate2:00remaining
Cursor behavior after iteration
After running the following code, what happens if you try to iterate over the cursor again?
MongoDB
var cursor = db.users.find(); while(cursor.hasNext()) { printjson(cursor.next()); } // Now iterate again while(cursor.hasNext()) { printjson(cursor.next()); }
Attempts:
2 left
💡 Hint
Think about how cursors work in MongoDB after reading all documents.
✗ Incorrect
Once a cursor is fully iterated, it is exhausted and has no more documents to return. You cannot iterate over it again without creating a new cursor.
📝 Syntax
advanced2:00remaining
Correct usage of pretty() with find()
Which of the following MongoDB shell commands correctly uses pretty() to format the output of a find query?
Attempts:
2 left
💡 Hint
pretty() is a method called on the cursor returned by find().
✗ Incorrect
pretty() is a method chained after find() to format the output. Calling pretty() before find() or passing it as an argument is invalid syntax.
❓ optimization
advanced2:00remaining
Improving performance when pretty printing large query results
You want to pretty print a large number of documents from a collection. Which approach is best to avoid performance issues?
Attempts:
2 left
💡 Hint
Consider how much data is processed and displayed at once.
✗ Incorrect
Limiting the number of documents reduces memory and processing load, making pretty printing faster and more responsive for large datasets.
🔧 Debug
expert2:00remaining
Diagnosing cursor error after pretty() usage
You run this code in the MongoDB shell:
var cursor = db.users.find().pretty();
printjson(cursor.next());
printjson(cursor.next());
But you get an error: "TypeError: cursor.next is not a function". What is the cause?
Attempts:
2 left
💡 Hint
Check what pretty() returns compared to find().
✗ Incorrect
pretty() formats the output as a string and does not return a cursor. Calling next() on the string causes a TypeError.