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: