Getting a single document in Firebase - Time & Space Complexity
When we get a single document from Firebase, we want to know how the time it takes changes as we ask for more documents.
We ask: How does the work grow when we get one document versus many?
Analyze the time complexity of the following operation sequence.
const docRef = firestore.collection('users').doc('user123');
docRef.get().then(doc => {
if (doc.exists) {
console.log('Document data:', doc.data());
} else {
console.log('No such document!');
}
});
This code fetches one specific document from the 'users' collection by its ID.
Identify the API calls, resource provisioning, data transfers that repeat.
- Primary operation: One API call to fetch a single document.
- How many times: Exactly once per document requested.
Getting one document requires one API call. If you get 10 documents separately, you make 10 calls.
| Input Size (n) | Approx. API Calls/Operations |
|---|---|
| 10 | 10 calls |
| 100 | 100 calls |
| 1000 | 1000 calls |
Pattern observation: The number of calls grows directly with the number of documents requested.
Time Complexity: O(1)
This means fetching a single document takes the same amount of time no matter how many documents exist in the database.
[X] Wrong: "Fetching one document gets slower as the database grows."
[OK] Correct: Firebase fetches documents by ID directly, so the time stays the same regardless of database size.
Understanding how single document fetches scale helps you explain efficient data access in real projects.
"What if we changed to fetching multiple documents in one batch request? How would the time complexity change?"