0

In my application users can like certain posts. Their likes will be stored in this way.

Image of the database:

enter image description here

Basically: in the collection Posts -> postID -> collection Likes -> userID -> timestamp. What I want to get is the number of userIds within the Likes collection for all posts. Basically I want to display the number of posts with the highest likes first in my Recycler Adapter.

I believe I am looking for a query of the type that would help me get the number of currentUserIds and then display them in descending order in my adapter:

Query firstQuery = firebaseFirestore.collection("Likes").document(currentUserId)...
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193

1 Answers1

0

(2022-10-20) Edit:

Starting from now, counting the documents in a collection or the documents that are returned by a query is actually possible without the need for keeping a counter. So you can count the documents using the new count() method which:

Returns a query that counts the documents in the result set of this query.

This new feature was announced at this year's Firebase summit. Keep in mind that this feature doesn't read the actual documents. So according to the [official documentation][2]:

For aggregation queries such as count(), you are charged one document read for each batch of up to 1000 index entries matched by the query. For aggregation queries that match 0 index entries, there is a minimum charge of one document read.

For example, count() operations that match between 0 and 1000 index entries are billed for one document read. For A count() operation that matches 1500 index entries, you are billed 2 document reads.


What I want to get is the number of userIds within the Likes collection for all posts.

In this case, you should perform a Firestore collection group query:

A collection group consists of all collections with the same ID. By default, queries retrieve results from a single collection in your database. Use a collection group query to retrieve documents from a collection group instead of from a single collection.

So in your case, you should use the following query:

db.collectionGroup("Likes").get().addOnCompleteListener(/* ... */);

To actually count the number of documents, please check my answer from the following post:

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193