Geting a field from a large number of firebase documents without it being to costly

I’m working on a project that will have a large number (thousands, possibly millions) of documents on a firebase collection, I need to access the average of the value by day of documents that are the same type, each one of them has a field “registered_value”, “date” and a “code” to identify its value and type and registered date.

I need to show users the average value by day of the documents that have the same code.

Users can add new documents, edit existing ones or delete the ones created by them

Since I need to get this data frequently it will be too expensive to always read the entire collection every time a user loads the pages that display this info is there a better way store or get the avarege?

I’m working with ReactJS and Node.js

Answer

There’s nothing built into Firestore to get aggregated values like that. The common approach is to store the aggregated value in a separate document somewhere, and update that document upon every relevant write operation. You can do this either from client-side code, or from Cloud Functions.

For more on this, see the Firebase documentation on aggregation queries and on distributed counters.