Comparison operators (==, <, >, >=, <=) in Firebase - Time & Space Complexity
When using comparison operators in Firebase queries, it's important to know how the number of comparisons grows as data increases.
We want to understand how many comparisons Firebase makes when filtering data with operators like ==, <, >, >=, and <=.
Analyze the time complexity of querying documents with a comparison filter.
const query = firestore.collection('users')
.where('age', '>=', 18)
.where('age', '<', 30)
.get();
query.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.data());
});
});
This code fetches users whose age is between 18 and 29 inclusive, using comparison operators in the query.
Let's find the main repeated actions in this query.
- Primary operation: Firebase performs comparisons on the 'age' field for each document in the collection or index.
- How many times: Once per document scanned or index entry checked.
As the number of documents grows, Firebase must check more entries to find matches.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | About 10 comparisons |
| 100 | About 100 comparisons |
| 1000 | About 1000 comparisons |
Pattern observation: The number of comparisons grows roughly in direct proportion to the number of documents scanned.
Time Complexity: O(n)
This means the time to complete the query grows linearly with the number of documents checked.
[X] Wrong: "Comparison queries always run instantly no matter how much data there is."
[OK] Correct: Firebase still needs to check documents or index entries to apply comparisons, so more data means more work.
Understanding how comparison operations scale helps you design efficient queries and shows you think about real-world data growth.
"What if we added an index on the 'age' field? How would that change the time complexity of these comparison queries?"