1

What is the best way to figure out how many documents are being created per hour into a Firestore collection. I have created a cloud functions which counts each time a document is added or removed but I can't seem to find a way to figure out the rate at which this is occurring.

1 Answers1

1

To solve this, you should add to each document in your collection a new property of type Date, that should hold the date and time of its creation. Now you can create a function, in Cloud Functions for Firebase that will add to a location in your database the number of documents added in the last hour. You can write this number in a Firebase realtime database rather than in Cloud Firestore, according to the last part of my answer within this post.

The function should actually count the number of documents using a query that look like this:

var today = new Date();
var lastHour = date.setDate(today.getDate() - 3600);
db.collection("nameOfCollection").where("date", ">", lastHour);

You can trigger this function using cron-job.org service.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Thank you for taking the time to answer this question. I appreciate your detailed response. I was wondering would it be possible to implement a metadata document for the collection containing the number of posts per hour updated in a similar fashion to this answer for large data sets https://stackoverflow.com/a/49407570/9367155 without having to query the whole database each time and count the snapshot, as with using chron-job this query would be performed every minute. – TheRedCamaro3.0 3.0 Nov 28 '18 at 19:34
  • Also Excellent answer on https://stackoverflow.com/questions/48534676/how-to-count-the-number-of-documents-under-a-collection-in-firestore/48540276#48540276 out of curiosity when you are talking about limits is sharding free in firebase but costly in firestore? – TheRedCamaro3.0 3.0 Nov 28 '18 at 19:35
  • Thank you for all of your help. Regarding the sharding, if I use Firebase real time database to store the counter instead of firestore would I still have to shard the data as is done here https://firebase.google.com/docs/firestore/solutions/counters or could I just make a counter node that constantly updates. Again thank you for all of your help. – TheRedCamaro3.0 3.0 Nov 29 '18 at 19:15
  • That solution is used only with Cloud Firestore. There is no need for that in Firebase realtime database. – Alex Mamo Nov 30 '18 at 11:08