Sling Academy
Home/Kotlin/Kotlin: How to Work with Collections and Documents in Firestore

Kotlin: How to Work with Collections and Documents in Firestore

Last updated: December 05, 2024

Google's Firebase Firestore is a NoSQL cloud database that simplifies application backend development and provides real-time database capabilities. When combined with Kotlin, a popular programming language for Android development, you have a powerful duo for building robust, responsive applications. This article explores how to work with collections and documents in Firestore using Kotlin.

Firestore organizes data in a structure of collections of documents. Each document can hold various types of data and supports complex nested objects to represent your application's data model.

Setting Up Firestore in Kotlin

Before diving into code, ensure you have Firebase set up in your Kotlin project. Here are the basic steps to get started:

  • Set up a Firebase project in your Google Cloud console.
  • Add the Firebase SDK dependencies to your build.gradle file:
  • Initialize Firebase in your Android Application class:

Working with Collections in Firestore

Firestore stores a collection of documents using a simple syntax in Kotlin. Let’s look at how to create, add to, and fetch data from a collection.

Creating and Adding a Document to a Collection

You can add data to a collection by specifying a collection path and creating a document:


val db = Firebase.firestore

val user = hashMapOf(
    "first" to "John",
    "last" to "Doe",
    "born" to 1990
)

db.collection("users")
    .add(user)
    .addOnSuccessListener { documentReference ->
        Log.d(TAG, "DocumentSnapshot added with ID: ${documentReference.id}")
    }
    .addOnFailureListener { e ->
        Log.w(TAG, "Error adding document", e)
    }

Fetching Documents from a Collection

Fetching documents involves querying the Firestore database. Here’s an example of how to retrieve all documents in the "users" collection:


db.collection("users")
    .get()
    .addOnSuccessListener { result ->
        for (document in result) {
            Log.d(TAG, "${document.id} => ${document.data}")
        }
    }
    .addOnFailureListener { exception ->
        Log.w(TAG, "Error getting documents.", exception)
    }

Querying and Sorting Data

Firestore supports robust querying directly in Kotlin. Let’s see some examples.

Querying Data

To query a collection documents with specific field values:


db.collection("users")
    .whereEqualTo("last", "Doe")
    .get()
    .addOnSuccessListener { documents ->
        for (document in documents) {
            Log.d(TAG, "${document.id} => ${document.data}")
        }
    }

Sorting and Limiting Results

Firestore allows sorting and limiting the result set. To order the "users" collection and limit the results:


db.collection("users")
    .orderBy("born")
    .limit(3)
    .get()
    .addOnSuccessListener { documents ->
        for (document in documents) {
            Log.d(TAG, "${document.id} => ${document.data}")
        }
    }

Updating and Deleting Documents

Updating or deleting documents in Firestore using Kotlin is straightforward.

Updating Documents

Use the following code snippet to update a field in an existing document:


val userRef = db.collection("users").document("user-id")
userRef
    .update("born", 1991)
    .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!") }
    .addOnFailureListener { e -> Log.w(TAG, "Error updating document", e) }

Deleting Documents

To delete a document:


val userRef = db.collection("users").document("user-id")
userRef
    .delete()
    .addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully deleted!") }
    .addOnFailureListener { e -> Log.w(TAG, "Error deleting document", e) }

Conclusion

Kotlin, alongside Firestore, provides a powerful and flexible platform for managing application data. Whether you’re storing simple key-value pairs, complex arrays, or deeply nested objects, Firestore offers dynamic scalability and powerful query capabilities to suit your development needs. These examples illustrate the simplicity with which you can interact with your Firestore database directly from Kotlin, enabling efficient and modern Android app development.

Next Article: Handling Realtime Data Updates with Firebase and Kotlin

Previous Article: Kotlin: Using Firebase Firestore for Data Storage and Retrieval

Series: Kotlin - Interacting with Databases

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin