Search code examples
dartgoogle-cloud-firestore

Listen to Firestore count()


Is it possible to listen to count() changes of a Firestore collection?

The example below fetches the current count of unread messages.

I could listen to the complete messages-collection and trigger a call to count() everytime the collection is updated.

Is there a more elegant way?

final unreadCount = await FirebaseFirestore.instance
        .collection('messages')
        .where('dateRead', isEqualTo: null)
        .where(Filter.or(Filter("selfUid", isEqualTo: selfUid),
            Filter("partnerUid", isEqualTo: selfUid)))
        .count()
        .get();

print(unreadCount.count);

Solution

  • No. It's stated pretty clearly in the documentation:

    You cannot use aggregation queries with real-time listeners and offline queries. Aggregation queries are only supported via direct server response.

    Count, sum, and average are all aggregation queries and all have the same limitation.