MongoDB with GraphQL - Time & Space Complexity
When using GraphQL to query data from MongoDB, it's important to understand how the time to get results grows as the data size increases.
We want to know how the number of operations changes when we ask for more or fewer records.
Analyze the time complexity of the following GraphQL query fetching multiple documents from MongoDB.
query GetBooks($limit: Int) {
books(limit: $limit) {
title
author
publishedYear
}
}
This query asks MongoDB to return a list of books with some fields, limited by a number we provide.
Look for repeated actions that take time as input grows.
- Primary operation: Retrieving each book document from the database.
- How many times: Once for each book requested, up to the limit.
As we ask for more books, the work grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document fetches |
| 100 | About 100 document fetches |
| 1000 | About 1000 document fetches |
Pattern observation: Doubling the number of books roughly doubles the work.
Time Complexity: O(n)
This means the time to get results grows linearly with the number of books requested.
[X] Wrong: "Fetching more books will take the same time as fetching just one because the database is fast."
[OK] Correct: Each book requires a separate fetch operation, so more books mean more work and more time.
Understanding how data fetching scales helps you design efficient queries and explain your choices clearly in interviews.
"What if we added filtering conditions to the query? How would that affect the time complexity?"