Excluding fields from results in MongoDB - Time & Space Complexity
When we ask a database to exclude certain fields from the results, it needs to check each item to remove those parts.
We want to know how the time it takes changes as the number of items grows.
Analyze the time complexity of the following code snippet.
db.collection.find({}, { password: 0, secretKey: 0 })
This code fetches all documents but leaves out the password and secretKey fields from each result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database scans each document to remove the specified fields.
- How many times: Once for every document returned.
As the number of documents grows, the database must process more items to exclude fields.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 field removals |
| 100 | 100 field removals |
| 1000 | 1000 field removals |
Pattern observation: The work grows directly with the number of documents.
Time Complexity: O(n)
This means the time to exclude fields grows in a straight line as more documents are processed.
[X] Wrong: "Excluding fields makes the query instant no matter how many documents there are."
[OK] Correct: The database still looks at every document to remove fields, so more documents mean more work.
Understanding how excluding fields affects time helps you explain how queries scale in real projects.
"What if we added a filter to only return 10 documents instead of all? How would the time complexity change?"