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?
Practice
Solution
Step 1: Understand Firestore data structure
Firestore stores data in collections and documents. Documents can contain subcollections.Step 2: Define subcollection purpose
A subcollection is a collection inside a document used to organize related data hierarchically.Final Answer:
A collection nested inside a document to organize related data -> Option CQuick Check:
Subcollection = nested collection inside document [OK]
- Thinking subcollections are special documents
- Confusing subcollections with backups
- Assuming subcollections auto-delete data
comments inside a document with ID post1 in the posts collection?Solution
Step 1: Identify the correct chaining method
To access a subcollection, first get the parent collection, then the document, then the subcollection.Step 2: Match the correct syntax
db.collection('posts').doc('post1').collection('comments') correctly chains collection('posts'), doc('post1'), then collection('comments').Final Answer:
db.collection('posts').doc('post1').collection('comments') -> Option DQuick Check:
Access subcollection by chaining collection, doc, collection [OK]
- Swapping doc and collection order
- Using doc() instead of collection() for subcollections
- Trying to access subcollection directly without parent doc
console.log(snapshot.docs.length) output if the comments subcollection has 3 documents?
const commentsRef = db.collection('posts').doc('post1').collection('comments');
const snapshot = await commentsRef.get();
console.log(snapshot.docs.length);Solution
Step 1: Understand what
Theget()returnsget()method on a collection reference returns a snapshot containing all documents in that collection.Step 2: Count documents in the snapshot
snapshot.docs.lengthgives the number of documents retrieved, which is 3 as stated.Final Answer:
3 -> Option AQuick Check:
Docs count in subcollection = 3 [OK]
- Assuming get() returns a single document
- Confusing docs.length with data length
- Expecting undefined if subcollection exists
const commentRef = db.collection('posts').collection('post1').collection('comments').doc();
await commentRef.set({ text: 'Nice post!' });
What is the error in this code?Solution
Step 1: Check the chaining of collection and doc
Subcollections must be accessed by first selecting the parent document withdoc('post1'), notcollection('post1').Step 2: Identify the incorrect method call
Usingcollection('post1')treats 'post1' as a collection, causing an error.Final Answer:
Using collection('post1') instead of doc('post1') to access the post document -> Option AQuick Check:
Access document with doc(), not collection() [OK]
- Confusing collection() and doc() methods
- Assuming doc() always needs an ID
- Thinking subcollections can't have new documents
Solution
Step 1: Consider Firestore best practices for related data
Storing comments as a subcollection inside each post keeps related data grouped and queries efficient.Step 2: Evaluate other options
Store all comments in a single top-level collection named 'comments' with a postId field can cause large collections and complex queries; Store comments inside the post document as an array field risks document size limits; Create a separate Firestore database for comments is unnecessary complexity.Final Answer:
Store comments as a subcollection inside each post document -> Option BQuick Check:
Subcollections keep related data organized and scalable [OK]
- Putting large arrays inside documents risking size limits
- Using one big collection causing slow queries
- Creating multiple databases unnecessarily
Ready to prove it?
Pass the test and this pattern moves unknown
