0

i have a collecntion Which Contain Multiple document and i want to fetch higest index document form it

Flow of data 1

Flow 2

Flow 3

I want to fetch Lat document of Customer_Info but i dont know it value

and i dont know how to implement orderBy in collections => Document => document_Data

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Nimesh
  • 49
  • 3

1 Answers1

1

If Bill_ID is same as the document ID, you can use orderBy() and limit(1) to get last document in that collection as shown below:

db.collection("(?)/Business/Customer_Info")
        .orderBy("Bill_ID", Direction.DESCENDING)
        .limit(1)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

However, you must ensure the field must be a number or the order will not be correct as Firestore orders them lexicographically.


You should avoid using sequential documents IDs and using a timestamp to order documents might be a better idea.

Also checkout:

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84