How to retrieve the last document from a Cloud Firestore collection? I would also like to get the document fields value.
Here this the image below:
Is there any way to get the last created document in Firebase Firestore collection? Yes, there is! The simplest way to achieve this is to add a date property to each object in your collection, then simply query it according to this new property descending and call limit(1) function. That's it!
A DocumentSnapshot contains data read from a document in your Cloud Firestore database. The data can be extracted with the getData() or get(String) methods. If the DocumentSnapshot points to a non-existing document, getData() and its corresponding methods will return null .
A QueryDocumentSnapshot contains data read from a document in your Cloud Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted using the getData() or the various get() methods in DocumentSnapshot (such as get(String) ).
Firebase data is retrieved by either a one time call to GetValueAsync() or attaching to an event on a FirebaseDatabase reference. The event listener is called once for the initial state of the data and again anytime the data changes.
How to retrieve the last document in a firebase collection?
To solve this, you need to use a query that should look like this:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
Query query = rootRef.collection("High Volume")
.orderBy("Time", Query.Direction.DESCENDING)
.limit(1);
query.get().addOnCompleteListener(/* ... */);
This query will order the results according to the time
property and will limit the results to one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With