Document-collection data model in Firebase - Time & Space Complexity
When working with Firebase's document-collection model, it is important to understand how the time to access or query data changes as your data grows.
We want to know how the number of operations changes when we read or write documents in collections.
Analyze the time complexity of the following code snippet.
const collectionRef = firestore.collection('users');
collectionRef.get().then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
});
This code fetches all documents from the 'users' collection and prints each document's data.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each document in the collection snapshot.
- How many times: Once for each document in the 'users' collection.
As the number of documents in the collection grows, the time to fetch and process all documents grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 document reads and loops |
| 100 | About 100 document reads and loops |
| 1000 | About 1000 document reads and loops |
Pattern observation: The operations increase directly with the number of documents.
Time Complexity: O(n)
This means the time to read all documents grows linearly with the number of documents in the collection.
[X] Wrong: "Fetching a collection always takes the same time regardless of size."
[OK] Correct: The time depends on how many documents you read; more documents mean more work and longer time.
Understanding how data size affects read time in Firebase helps you design efficient queries and data structures, a valuable skill in real projects and interviews.
"What if we only fetched documents with a filter instead of the whole collection? How would the time complexity change?"
Practice
Solution
Step 1: Understand Firebase data structure
Firebase stores data in documents, and these documents are grouped inside collections.Step 2: Identify the container for documents
The container that holds multiple documents is called a collection, not a table, row, or field.Final Answer:
A collection -> Option AQuick Check:
Documents are inside collections [OK]
- Confusing collections with tables from SQL
- Thinking documents are inside fields
- Mixing up rows with documents
user123 inside a collection users in Firebase?Solution
Step 1: Recall Firebase syntax for document reference
To get a document inside a collection, usecollection('name').doc('id').Step 2: Match the correct syntax
db.collection('users').doc('user123') usesdb.collection('users').doc('user123'), which is the standard way.Final Answer:
db.collection('users').doc('user123') -> Option AQuick Check:
Use collection then doc to reference documents [OK]
- Swapping collection and doc order
- Using dot notation like db.users('user123')
- Using doc with full path incorrectly
const docRef = db.collection('books').doc('book1');
await docRef.set({ title: 'Learn Firebase', pages: 150 });
const snapshot = await db.collection('books').get();
const titles = snapshot.docs.map(doc => doc.data().title);
console.log(titles);
What will be printed in the console if the 'books' collection was empty before?Solution
Step 1: Understand the code flow
The code adds a document 'book1' with title and pages to 'books' collection, then fetches all documents in 'books'.Step 2: Analyze the output of mapping titles
Since 'books' was empty before, after adding 'book1', the collection has one document with title 'Learn Firebase'. Mapping titles returns ['Learn Firebase'].Final Answer:
['Learn Firebase'] -> Option CQuick Check:
Added one doc, so titles list has one title [OK]
- Thinking snapshot is empty before set()
- Confusing document ID with title
- Expecting error due to async code
const userRef = db.collection('users').doc('user1');
userRef.get().then(doc => {
if (doc.exists) {
console.log(doc.data().name);
} else {
console.log('No such document!');
}
});
If the document 'user1' does not exist, what will be printed?Solution
Step 1: Check the existence condition
The code checks ifdoc.existsis true before accessing data.Step 2: Understand behavior when document missing
If the document does not exist,doc.existsis false, so it prints 'No such document!'.Final Answer:
'No such document!' -> Option BQuick Check:
doc.exists false triggers else block [OK]
- Trying to access data without checking doc.exists
- Expecting undefined or null instead of message
- Confusing doc.exists with doc.data()
Solution
Step 1: Understand hierarchical data in Firebase
Firebase supports subcollections inside documents, which is ideal for related nested data.Step 2: Choose the best structure for users and their multiple addresses
Using a 'users' collection with each user document having an 'addresses' subcollection keeps data organized and scalable.Final Answer:
A collection 'users' with documents for each user, each containing a subcollection 'addresses' with address documents -> Option DQuick Check:
Use subcollections for nested related data [OK]
- Storing all users and addresses in one big document
- Mixing user and address data in one collection without hierarchy
- Creating many collections named after users
Ready to prove it?
Pass the test and this pattern moves unknown
