How to query latest documents first? - flutter

I am using Flutter & Cloud Firestore. I have a collection. There are many documents in that collection. My question is how to fetch those documents on the time basis. Like I want to firstly show those documents data that I had added latest and the oldest documents data at the last. How to do that?

Considering you have a timestamp field (named addedAt for example) in your documents, you can use the orderBy method .orderBy('addedAt', descending: true)

Related

How to sort by a field in a sub-collection in firebase cloud firestore in flutter

I am trying to query a cloud firestore database and i need it to return all the documents in the chats collection sorted by the timestamp field which is a field that all the documents in the messages sub-collection have.
i tried writing a query like this.
FirebaseFirestore.instance.collection("chats").orderBy("messages.timestamp", descending: true)].get(),
but it does not return any documents when actually there are some documents there.
Firestore can only order or filter on data in the documents that it returns. There is no ability to order or filter on data outside of those documents.
So if we want to order chats in the timestamp of the last message in that chat (a common use-case), you'll have to include a lastMessageTimestamp field in the chat document itself, and update that whenever a message is written in its messages subcollection. With that lastMessageTimestamp field in place in each chats document, you can then order and filter on that.
Create a new collection called messages and store all messages for every user there (with a user id field). Reference the message uid's via an array in each chat. This way you can easily query for the messages associated with a chat session then sort them.

how to fetch all the documents below a specific doc from firebase flutter

how can we fetch all the document after a specific document from firebase flutter ? what I mean is for example we have 10 documents with respective id and order[1,2,3,4,5,6,7,8,9,10] in firebase I want to fetch documents from [1 to 5]once then [6 to 10] in next call .some thing for state management loading a certain number of documents once then another range of documents in next call and so on and reflect in User Interface accordingly.
please help me in this regards..
Firestore has a startAfterDocument method that can be used to query collections after a certain index based on the document. You can first query the collection and set limit to the number of documents retrieved using
firestore.collection('example').limit(5).get(). With this result you can store the last document and use it for the next queries as such:
firestore.collection('example').startAfterDocument(lastDocumentInPreviousQuery).limit(5)
Just make sure you always store the last document that was retrieved in a query to ensure you get the correct result.

Query firebase docs by subcollection value

I have a Firebase Firestore DB with this structure:
Users (collection) -> user (doc) -> Reports (subcollection) -> report (doc) -> isHandled (bool field).
In my Flutter app, I want to query Users collection, and get only the user docs in which any of their reports collection docs is not handled (isHandled field == false).
I've tried to use Firestore's collectionGroup, but it returns only 1 report doc, instead of many user docs:
await FirebaseFirestore.instance
.collectionGroup('Reports')
.where(
'isHandled',
isEqualTo: false,
)
.get();
Does Firebase Firestore support any query of a collection by its docs' subcollection values?
Thank you very much in advance!
Does Firebase Firestore support any query of a collection by its docs' subcollection values?
No. When you query a collection or subcollection, it will only consider documents immediately within it. The data from a single collection's documents is managed by an "index" - queries only use that index to rapidly find data at scale.
Collection group queries are special in that they consider all collections with the same name, but they will still not consider nested subcollections.
You could perhaps combine a collection group query with further queries to get the "parent" user document from a matched report.

Firestore how to query documents chronologically

I understand that unlike Firebase Realtime DB, there isn't a built in method for querying Firestore documents chronologically.
Other than adding a timestamp field to each document, is there another elegant way to achieve that?
Apparently it isn't recommended to name documents in an ascending names (Do not use monotonically increasing document IDs)

Sort documents in firestore collection chronologically

Is there a way to sort documents in collection chronologically when they are created? Currently, they are all over the place. For example, in To-Do app, when you add new item to collection, it should display at the bottom, last, not somewhere in the middle.
You will need to define an order based on some data in the document, and order your queries based on that field.
The typical solution for time-base order to make sure your documents all contain a timestamp field that you can use to sort them. When you call add() (or other methods to update data), you can tell Firestore to use the current time using FieldValue.serverTimestamp():
collection(...).add({
..., // your other fields
createdOn: FieldValue.serverTimestamp()
})
Then you can use that field to sort when querying with orderBy():
collection(...).orderBy('createdOn')
Try using DateTime.now() for the document ID. This should put the collection in chronological order.
For example:
Firestore.instance.collection('Posts').document(DateTime.now().toString()).setData({});