Home > Software engineering >  How to sort by a field in a sub-collection in firebase cloud firestore in flutter
How to sort by a field in a sub-collection in firebase cloud firestore in flutter

Time:01-15

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.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related