1

I am trying to make a function that counts the number of documents in a collection. This collection contains the users that the user follows, so it can be many documents. I am concerned that each user sees the number of followers count all the documents and count them to me as reads.

Is there a way to count documents if it counts as reads?

Function:

func fetchUserStats() {
            guard let uid = user.id else {return}
            
            COLLECTION_FOLLOWING.document(uid).collection("user-following").getDocuments { snapshot, _ in
                guard let following = snapshot?.documents.count else { return }
            
                COLLECTION_FOLLOWERS.document(uid).collection("user-followers").getDocuments { snapshot, _ in
                guard let followers = snapshot?.documents.count else { return }
 
                self.user.stats = UserStats(following: following, followers: followers)
                           }

        }
        }

This function counts the number of documents in the collection, so each time a user sees the profile, it counts the documents and shows them the total.

How can I make it so that it does not count me as reads, or some more functional way?

Thanks

jnpdx
  • 45,847
  • 6
  • 64
  • 94
  • There are no built-in aggregation operations in Cloud Firestore. So unless you build something yourself (as shown [here](https://firebase.google.com/docs/firestore/solutions/aggregation) and [here](https://firebase.google.com/docs/firestore/solutions/counters)), reading all documents is indeed the only way to get the count - and will indeed linearly increase in cost with the number of documents in the collection. – Frank van Puffelen Nov 17 '21 at 20:49
  • You can achieve this by using Algolia and the Firebase Extension. Algolia will not only return `nbHits` (total count) but can also count facets (count per value). The downside is that you'll have the additional cost of implementing Algolia, but it will scale much better. – Jason Berryman Nov 17 '21 at 21:43

0 Answers0