Getting all documents in collection in Firebase - Time & Space Complexity
When we get all documents from a collection in Firebase, we want to know how the time it takes changes as the collection grows.
We ask: How does fetching more documents affect the work done?
Analyze the time complexity of the following code snippet.
const querySnapshot = await getDocs(collection(db, "users"));
querySnapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
This code fetches all documents from the "users" collection and then processes each document one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each document in the collection.
- How many times: Once for every document in the collection.
As the number of documents grows, the time to fetch and process them grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document fetch and process steps |
| 100 | About 100 document fetch and process steps |
| 1000 | About 1000 document fetch and process steps |
Pattern observation: The work grows directly with the number of documents.
Time Complexity: O(n)
This means the time to get all documents grows in a straight line as the collection gets bigger.
[X] Wrong: "Fetching all documents takes the same time no matter how many there are."
[OK] Correct: Each document adds extra work, so more documents mean more time needed.
Understanding how data size affects fetching time helps you write better queries and explain your code clearly in real projects.
"What if we only fetched documents with a filter that returns half the collection? How would the time complexity change?"