Home > database >  Firebase collection group limit for each collection
Firebase collection group limit for each collection

Time:11-01

I have a Firestore problem querying data. I have a collection called conversations. Within each conversation document, there is a collection called messages. Each message has a field time, which is a timestamp.

How do I query a collection group such that I get the most recent message in each conversation?

I am using the SDK for the web, version 9.

CodePudding user response:

That doesn't seem to be possible with a collection group query. Using .orderBy() will sort all document in messages sub-collection. You might have to get list of all user conversations and then fetch last message from each conversation individually.

Do note that using .collectionGroup('messages') will look for documents in all collections named as messages including other users. So make sure you have some filters there.

You can store last message in conversation document itself but that'll incur and additional write every time a new message is added.

  • Related