Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the last document in a firebase collection. I would also like to get the document fields value

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:

enter image description here

like image 882
user10373549 Avatar asked Sep 17 '18 06:09

user10373549


People also ask

How do I get most recent documents on firestore?

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!

What is document snapshot in Firebase?

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 .

How do I get data from QueryDocumentSnapshot?

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) ).

How do I get data from Firebase?

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.


1 Answers

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.

like image 161
Alex Mamo Avatar answered Oct 15 '22 19:10

Alex Mamo