Maximum value from Firebase Firestore collection

Viewed 9201
collection
        *
        Random_Id1
                *amount:100
                *name:John
        Random_Id2
                *amount:150
                *name:Matt
        Random_Id3
                *amount:65
                *name:Alice

I have a firestore collection that has different documents under it. these documents have data within them(name,age,amount, etc.). is there a way i can return the highest or Maximum amount in the collection? I'm implementing this in java(android). In the case of the above structure, the Maximum will be 150. Thank you in advance

3 Answers

In Kotlin, you can do it like this:

db.collection("collection")
   .orderBy("amount", Direction.DESCENDING).limit(1)
   .get()
   .addOnSuccessListener { documents ->
           //your code, print the highest amount   
   }                
   .addOnFailureListener { exception ->
           Toast.makeText(this, exception.toString(), Toast.LENGTH_LONG).show()
           Log.i("YourActivity",exception.toString())
    }

Then, run your project and trigger the above call to the database. You will see a toast with a firebase exception message. Go to your Logcat, filter it with YourActivity class name, and you will see there a link to Firebase, in order to confirm this new index that you are creating. Wait for it's building a few minutes, and when it's status is enabled, run your project again.

const maxRef = await db.collection('collection').orderBy('amount', 'desc').limit(1).get();
const dataRef = maxRef.docs? maxRef.docs[0] : null;
console.log(dataRef.data())

reference

Related