Pretty printing and cursor behavior in MongoDB - Time & Space Complexity
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?"