2

I have a pretty large collection of documents in Firestore with random IDs and each one of those documents has two fields, a name and a description. I want my app to allow the user to enter a series of characters and then present to him all the documents which contain that sequence of chars in let's say the name field. Is this feasible using Firebase & its queries and if so, could you give me a code example in Kotlin or Java? I know there are some methods such as hasChild() or child("child name").exists() but since i don't yet know which document the user is looking for i can't use them if i'm not mistaken.

For example, if i had a collection of 3 documents which had the following names ("mike","michael","dave") and the user entered "mi", i'd like to be able to retrieve the documents whose names are "mike" & "michael".

Romanas
  • 547
  • 7
  • 25
Stelios Papamichail
  • 955
  • 2
  • 19
  • 57

1 Answers1

9

If you want to get all documents where the name field starts with mi, you can do so with:

db.collection("users")
  .whereGreaterThanOrEqualTo("name", "mi")
  .whereLessThanOrEqualTo("name", "mi\uF7FF")
  .get()
  .addOnSuccessListener { documents ->
    for (document in documents) {
      Log.d(TAG, "${document.id} => ${document.data}")
    }
  }
    .addOnFailureListener { exception ->
        Log.w(TAG, "Error getting documents: ", exception)
    }

The \uF7FF value used here is the last Unicode character that exists, so this:

  1. Orders all documents by their name value
  2. Finds the first document that starts with mi
  3. returns all documents, until it reaches one that's bigger than mi

For much more on this, read the Firebase documentation on querying data.

I also recommend checking out these related questions:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Where can I find the API docs for `whereGreaterThanOrEqualTo()` ? – Greg Fenton Jan 29 '21 at 01:48
  • 1
    Ah, found it. Surprisingly it did not show up in a google search for "firestore whereGreaterThanOrEqualTo". But it is here: https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Query#whereGreaterThanOrEqualTo(java.lang.String,%20java.lang.Object) – Greg Fenton Jan 29 '21 at 01:51