Querying with where clause in Firebase - Time & Space Complexity
When we use a where clause in Firebase queries, we want to know how the time to get results changes as the data grows.
We ask: How does the query speed change when there are more records to check?
Analyze the time complexity of the following code snippet.
const db = getFirestore();
const q = query(collection(db, "users"), where("age", ">", 18));
const querySnapshot = await getDocs(q);
querySnapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
This code fetches all users older than 18 from the database.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the user records to find those with age > 18.
- How many times: Once for each user record in the collection.
As the number of users grows, the query checks more records to find matches.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The number of checks grows directly with the number of users.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of records grows.
[X] Wrong: "The where clause instantly finds the data no matter how big the collection is."
[OK] Correct: Without an index, Firebase must check each record, so more data means more time.
Understanding how queries scale helps you write efficient database code and explain your choices clearly.
"What if we added an index on the age field? How would the time complexity change?"