Subcollections in Firebase - Time & Space Complexity
When using subcollections in Firebase, it's important to understand how the number of operations grows as you access nested data.
We want to know how the time to get data changes when we have many subcollections.
Analyze the time complexity of reading documents from multiple subcollections.
const db = firebase.firestore();
async function readSubcollections(parentId) {
const subcollections = await db.collection('parents').doc(parentId).listCollections();
for (const subcol of subcollections) {
const docs = await subcol.get();
docs.forEach(doc => console.log(doc.id));
}
}
This code lists all subcollections of a parent document, then reads all documents in each subcollection.
Look at what repeats as input grows.
- Primary operation: Reading each subcollection's documents with
subcol.get(). - How many times: Once per subcollection under the parent document.
As the number of subcollections grows, the number of read operations grows too.
| Input Size (n subcollections) | Approx. Api Calls/Operations |
|---|---|
| 10 | About 10 reads (one per subcollection) |
| 100 | About 100 reads |
| 1000 | About 1000 reads |
Pattern observation: The number of reads grows directly with the number of subcollections.
Time Complexity: O(n)
This means the time to read all subcollections grows linearly as you add more subcollections.
[X] Wrong: "Reading subcollections is just one operation regardless of how many there are."
[OK] Correct: Each subcollection requires its own read call, so more subcollections mean more operations.
Understanding how nested data access scales helps you design efficient data models and answer questions about performance in real projects.
What if we batch read documents from all subcollections at once? How would the time complexity change?