Firestore Read Operations — Complete Guide
In this tutorial, you'll learn about Firestore Read Operations. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your Firestore query returns no results when data exists, or you get PERMISSION_DENIED on read, or a single document read charges you for the whole collection.
Wrong Approach ❌
// Reading all documents to find one
db.collection("users")
.get()
.addOnSuccessListener { documents ->
for (doc in documents) {
if (doc.id == userId) { // Client-side filter — expensive!
// Process document
}
}
}
Output: Client-side filtering reads every user document. Massive read bill.
Right Approach ✅
class UserRepository(private val db: FirebaseFirestore) {
// Direct document read — 1 read
suspend fun getUser(userId: String): User? {
return try {
val doc = db.collection("users").document(userId).get().await()
doc.toObject(User::class.java)
} catch (e: FirebaseFirestoreException) {
when (e.code) {
Code.PERMISSION_DENIED -> logError("Permission denied")
Code.NOT_FOUND -> null
else -> throw e
}
null
}
}
// Query with filter — server-side filtering
suspend fun getUsersByAge(minAge: Int): List<User> {
return try {
db.collection("users")
.whereGreaterThanOrEqualTo("age", minAge)
.orderBy("age")
.limit(50)
.get().await()
.toObjects(User::class.java)
} catch (e: Exception) {
emptyList()
}
}
// Paginated query
suspend fun getUsersPaginated(
lastVisible: DocumentSnapshot?,
pageSize: Long = 20
): Pair<List<User>, DocumentSnapshot?> {
var query = db.collection("users")
.orderBy("name")
.limit(pageSize)
lastVisible?.let { query = query.startAfter(it) }
val snapshot = query.get().await()
val users = snapshot.toObjects(User::class.java)
val lastDoc = snapshot.documents.lastOrNull()
return Pair(users, lastDoc)
}
// Compound query with composite index required
suspend fun getActiveUsersInCity(city: String): List<User> {
return try {
db.collection("users")
.whereEqualTo("city", city)
.whereEqualTo("isActive", true)
.get().await()
.toObjects(User::class.java)
} catch (e: FirebaseFirestoreException) {
if (e.code == Code.FAILED_PRECONDITION) {
// Create composite index in Firebase Console
logError("Create composite index for city + isActive")
}
emptyList()
}
}
}
Output: Efficient reads with proper server-side filtering.
Prevention
- Always filter at the database level with
where*clauses. - Design queries to use existing indexes.
- Use
.limit()to cap read costs. - Use
.startAfter()/.endBefore()for pagination instead of offsets. - Monitor read counts in Firebase Console.
Common Mistakes with firestore read
- Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro