Bird
Raised Fist0
MongoDBquery~10 mins

Pretty printing and cursor behavior in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Pretty printing and cursor behavior
Run find() query
Get cursor object
Iterate cursor to fetch documents
Pretty print each document
Cursor exhausted?
NoFetch next document
Yes
End
This flow shows how a MongoDB find() query returns a cursor, which you iterate to get documents, printing each in a readable format until no documents remain.
Execution Sample
MongoDB
cursor = db.collection.find({})
for doc in cursor:
    print(doc)
This code runs a query to get all documents, then prints each document one by one.
Execution Table
StepActionCursor StateDocument FetchedOutput (Pretty Printed Document)
1Run find() queryCursor created, points before first documentNone yetNo output yet
2Fetch first documentCursor at first document{_id:1, name:'Alice'}{ _id: 1, name: 'Alice' }
3Fetch second documentCursor at second document{_id:2, name:'Bob'}{ _id: 2, name: 'Bob' }
4Fetch third documentCursor at third document{_id:3, name:'Carol'}{ _id: 3, name: 'Carol' }
5No more documentsCursor exhaustedNoneNo output, loop ends
💡 Cursor has no more documents, iteration ends
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
cursorNonePoints to first documentPoints to second documentPoints to third documentExhausted (no more docs)
docNone{_id:1, name:'Alice'}{_id:2, name:'Bob'}{_id:3, name:'Carol'}None
Key Moments - 2 Insights
Why does the cursor not return all documents at once?
The cursor fetches documents one by one to save memory and allow processing large datasets. See execution_table steps 2-4 where each document is fetched individually.
What happens when the cursor reaches the last document?
When the cursor has no more documents, iteration stops as shown in execution_table step 5 where the cursor is exhausted and no output is printed.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what document does the cursor point to after step 3?
A{_id:1, name:'Alice'}
B{_id:2, name:'Bob'}
C{_id:3, name:'Carol'}
DNo document, cursor exhausted
💡 Hint
Check the 'Cursor State' and 'Document Fetched' columns at step 3 in the execution_table.
At which step does the cursor become exhausted?
AStep 5
BStep 2
CStep 4
DStep 3
💡 Hint
Look at the 'Cursor State' column in execution_table; exhaustion is noted at step 5.
If the collection had 5 documents instead of 3, how would the variable 'doc' change after step 4?
Adoc would be None
Bdoc would hold the 3rd document
Cdoc would hold the 4th document
Ddoc would hold all 5 documents
💡 Hint
Refer to variable_tracker and execution_table showing doc updates per step.
Concept Snapshot
MongoDB find() returns a cursor object.
Cursor fetches documents one at a time.
Iterate cursor to get each document.
Print documents for readable output.
Cursor ends when no documents remain.
Full Transcript
When you run a MongoDB find() query, it returns a cursor. This cursor points to the first document but does not load all documents at once. You then iterate over the cursor to fetch each document one by one. Each document can be printed in a pretty format for easy reading. The cursor moves forward with each fetch until it has no more documents, at which point the iteration ends. This approach helps manage memory and handle large data sets efficiently.

Practice

(1/5)
1. What does the pretty() method do when used after a MongoDB query?
easy
A. Formats the output to be more readable with indentation and line breaks
B. Limits the number of documents returned by the query
C. Sorts the documents in ascending order
D. Deletes the documents matching the query

Solution

  1. Step 1: Understand the purpose of pretty()

    The pretty() method formats the output of a query to make it easier to read by adding indentation and line breaks.
  2. Step 2: Compare with other options

    Limiting, sorting, or deleting documents are done by other methods like limit(), sort(), or remove(), not pretty().
  3. Final Answer:

    Formats the output to be more readable with indentation and line breaks -> Option A
  4. Quick Check:

    pretty() improves readability [OK]
Hint: Remember: pretty() just makes output look nicer [OK]
Common Mistakes:
  • Confusing pretty() with limit() or sort()
  • Thinking pretty() changes the data
  • Assuming pretty() affects query results count
2. Which of the following is the correct syntax to check if a MongoDB cursor has more documents to iterate?
easy
A. cursor.hasMore()
B. cursor.hasNext()
C. cursor.nextExists()
D. cursor.more()

Solution

  1. Step 1: Recall cursor methods in MongoDB

    The correct method to check if a cursor has more documents is hasNext().
  2. Step 2: Verify other options

    Methods like hasMore(), nextExists(), or more() do not exist in MongoDB cursor API.
  3. Final Answer:

    cursor.hasNext() -> Option B
  4. Quick Check:

    Use hasNext() to check cursor availability [OK]
Hint: Use hasNext() to check cursor's next document [OK]
Common Mistakes:
  • Using non-existent cursor methods
  • Confusing hasNext() with next()
  • Assuming hasNext() returns the document itself
3. Given the following MongoDB shell commands, what will be the output?
var cursor = db.users.find({age: {$gt: 25}}).pretty();
while(cursor.hasNext()) {
  printjson(cursor.next());
}
medium
A. No output because cursor.next() is missing parentheses
B. Syntax error because pretty() cannot be chained with find()
C. All user documents with age greater than 25 printed in readable JSON format
D. Only the first user document with age greater than 25 printed

Solution

  1. 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.
  2. Step 2: Understand the output behavior

    Each matching document is printed in readable JSON format until no documents remain.
  3. Final Answer:

    All user documents with age greater than 25 printed in readable JSON format -> Option C
  4. Quick Check:

    Cursor iterates all matching docs with pretty print [OK]
Hint: pretty() formats output; hasNext() and next() iterate all [OK]
Common Mistakes:
  • Thinking pretty() breaks chaining
  • Assuming only one document prints
  • Forgetting to call next() as a function
4. You run this code in MongoDB shell:
var cursor = db.products.find().pretty();
if(cursor.hasNext) {
  printjson(cursor.next());
}
What is the problem with this code?
medium
A. hasNext is used without parentheses, so it does not check correctly
B. pretty() cannot be used with find()
C. next() should be called before hasNext()
D. printjson() cannot print cursor documents

Solution

  1. Step 1: Identify method usage errors

    The method hasNext is used without parentheses, so it refers to the function itself, not its boolean result.
  2. Step 2: Understand impact on code behavior

    Because hasNext is not called, the if condition always evaluates to true (function exists), causing unexpected behavior.
  3. Final Answer:

    hasNext is used without parentheses, so it does not check correctly -> Option A
  4. Quick Check:

    Always call hasNext() with parentheses [OK]
Hint: Call hasNext() with () to get boolean result [OK]
Common Mistakes:
  • Using hasNext without parentheses
  • Thinking pretty() causes error
  • Calling next() before checking hasNext()
5. You want to print all documents from the 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?
hard
A. var cursor = db.orders.find({status: "shipped"}).batchSize(3); cursor.pretty(); while(cursor.hasNext()) { printjson(cursor.next()); }
B. var cursor = db.orders.find({status: "shipped"}).pretty(); for(var i=0; i<3; i++) { printjson(cursor.next()); }
C. var cursor = db.orders.find({status: "shipped"}).pretty(); while(cursor.hasNext()) { printjson(cursor.next()); if(i==3) break; }
D. var cursor = db.orders.find({status: "shipped"}).limit(3).pretty(); while(cursor.hasNext()) { printjson(cursor.next()); }

Solution

  1. Step 1: Limit query results to 3 documents

    Using limit(3) restricts the cursor to only 3 documents matching the filter.
  2. Step 2: Use pretty() to format output and iterate with hasNext()/next()

    Chaining pretty() formats output. The while loop prints each document until the 3 limited documents are exhausted.
  3. Final Answer:

    var cursor = db.orders.find({status: "shipped"}).limit(3).pretty(); while(cursor.hasNext()) { printjson(cursor.next()); } -> Option D
  4. Quick Check:

    limit(3) + pretty() + hasNext()/next() prints 3 formatted docs [OK]
Hint: Use limit(3) before pretty() and iterate with hasNext()/next() [OK]
Common Mistakes:
  • Not using limit() to restrict documents
  • Calling pretty() after iteration instead of chaining
  • Incorrect loop control causing infinite or missing output