Firestore collections and documents in GCP - Time & Space Complexity
When working with Firestore, it's important to understand how the time to access data grows as you add more collections and documents.
We want to know how the number of operations changes when we read or write many documents.
Analyze the time complexity of reading multiple documents from a Firestore collection.
// Fetch all documents from a collection
const collectionRef = firestore.collection('users');
const snapshot = await collectionRef.get();
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
This code fetches all documents inside the 'users' collection and processes each one.
Look at what repeats when fetching documents:
- Primary operation: Reading each document from the collection.
- How many times: Once per document in the collection.
As the number of documents grows, the number of reads grows too.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 document reads |
| 100 | 100 document reads |
| 1000 | 1000 document reads |
Pattern observation: The number of reads grows directly with the number of documents.
Time Complexity: O(n)
This means the time to read documents grows linearly with how many documents you have.
[X] Wrong: "Reading a collection is always a single fast operation regardless of size."
[OK] Correct: Firestore reads each document separately, so more documents mean more reads and more time.
Understanding how Firestore scales with data size helps you design efficient queries and avoid slow operations in real projects.
"What if we added a filter to only read documents matching a condition? How would the time complexity change?"
Practice
Solution
Step 1: Understand Firestore data hierarchy
Firestore organizes data with collections at the top level, which hold documents.Step 2: Identify what documents contain
Documents store data as key-value pairs, not collections directly.Final Answer:
Collections contain documents, and documents contain key-value pairs. -> Option DQuick Check:
Firestore data = collections > documents > key-value pairs [OK]
- Thinking documents hold collections directly
- Assuming collections store key-value pairs without documents
- Confusing the order of collections and documents
user123 inside a collection users in Firestore using Node.js?Solution
Step 1: Identify correct method to access collection and document
Usecollection('users')to access the collection, thendoc('user123')to get the document.Step 2: Check path correctness
Directfirestore.doc(full/path)works for existing paths, but incorrect paths, reversed order, or misusingdoc()on document references fail. Chainingcollection().doc()is recommended.Final Answer:
const docRef = firestore.collection('users').doc('user123'); -> Option BQuick Check:
Use collection().doc() chaining for document refs [OK]
- Swapping collection and document names
- Using firestore.doc() with incorrect path format
- Confusing collection() and doc() order
user123 exists with fields {name: 'Alice', age: 30}?
const docRef = firestore.collection('users').doc('user123');
const docSnap = await docRef.get();
if (docSnap.exists) {
console.log(docSnap.data());
} else {
console.log('No such document!');
}Solution
Step 1: Check if document exists
The code checksdocSnap.exists, which is true if the document is present.Step 2: Output document data
If exists,docSnap.data()returns the document fields as an object.Final Answer:
{ name: 'Alice', age: 30 } -> Option CQuick Check:
docSnap.exists true means data() returns fields [OK]
- Assuming data() returns undefined if document exists
- Confusing exists check with data presence
- Expecting error instead of 'No such document!' message
const docRef = firestore.collection('users').doc();
const docSnap = await docRef.get();
What is the problem?Solution
Step 1: Check doc() usage
Callingdoc()without an ID creates a reference to a new document with an auto-generated ID, but it does not exist yet.Step 2: Understand get() on new doc reference
Trying to get() returns a snapshot withexists=falsebecause the document does not exist.Final Answer:
Missing document ID in doc() causes a reference to a non-existing document. -> Option AQuick Check:
doc() needs ID to get existing document [OK]
- Assuming doc() without ID points to existing document
- Thinking get() cannot be called on document references
- Confusing collection and document method usage
Solution
Step 1: Understand Firestore best practice for one-to-many
Use a main collection for users, and subcollections for related multiple items like addresses.Step 2: Evaluate options
A collection 'users' with documents for each user, and each user document has a subcollection 'addresses' with address documents. uses subcollections for addresses, which is scalable and organized. A single collection 'addresses' with documents containing user info and address fields combined. mixes user and address data in one collection, which is less clear. A collection 'users' where each document stores all addresses as a large array field. stores all addresses in one field, which can be inefficient. Multiple collections named after each user ID, each containing address documents. creates many collections dynamically, which is not recommended.Final Answer:
A collection 'users' with documents for each user, and each user document has a subcollection 'addresses' with address documents. -> Option AQuick Check:
Use subcollections for related multiple items [OK]
- Storing multiple addresses in one array field causing size limits
- Creating dynamic collections per user causing management issues
- Mixing unrelated data in one collection
Ready to prove it?
Pass the test and this pattern moves unknown
