I have a Countries
collection and inside this collection, There are 195 countries, And the admin can add or delete any country.
In my android app, I want to know how many countries are currently there without reading all countries again because that will cost me 195 read for each user, So I decided to create a counter for this but the question is where should I put the counter? Should I create a new collection for just that counter?
CodePudding user response:
There is no singular correct answer for this, so I'll illustrate some patterns I've seen used instead.
The distributed counter example in the documentation stores the counter documents in a top-level shards
collection. That's a good starting point, although I'd probably name it something like counters
, metadata
or counters
.
In the Cloud Functions example of a child node counter for Realtime Database, we store the counter as a sibling property of the node that holds the children. So you have likes
(which hold the actual likes) and likes_count
, which is the counter. In Firestore that structure could also work if the count isn't global, but you're counting a subcollection of a specific document.
Finally I did some experimenting with geo-indexes myself a while ago, and there I put my counter documents in the same collection as the documents they counted, but then with a predictable name. The documents had prefix-based IDs, so I ended up with count documents geodocs-2 counts
, geodocs-3 counts
, etc.
Each of these is a good practice for the use-case in question, and can likely be applied to many other use-case as well. But I'm guessing there are many more reasonable, workable strategies for other cases too.