0
0
Firebasecloud~5 mins

Subcollections in Firebase - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Subcollections
O(n)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of subcollections grows, the number of read operations grows too.

Input Size (n subcollections)Approx. Api Calls/Operations
10About 10 reads (one per subcollection)
100About 100 reads
1000About 1000 reads

Pattern observation: The number of reads grows directly with the number of subcollections.

Final Time Complexity

Time Complexity: O(n)

This means the time to read all subcollections grows linearly as you add more subcollections.

Common Mistake

[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.

Interview Connect

Understanding how nested data access scales helps you design efficient data models and answer questions about performance in real projects.

Self-Check

What if we batch read documents from all subcollections at once? How would the time complexity change?