Calculate SUM and AVG aggregations using Firestore
Frequently, Firestore customers need to calculate a sum or average on a particular field across their documents. With today’s launch of SUM() and AVG() aggregation functions, Firestore customers can easily calculate aggregations like the total profit for merchandise sales using SUM(), or the average distance traveled by all fleet vehicles using AVG().
To use this feature, simply specify the aggregation function and the field name. Firestore computes the SUM() and AVG() results directly through index scans. This makes it efficient, but also means that a field must be indexed to calculate an aggregation.
For example, if we have a collection called “tripsCollection”, in order to get the total distance by vehicles that are of type “motorcycle”, you could run the below query:
It’s just as easy to find the average distance traveled as well:
Multiple aggregators can also be specified in one query. For example, both the AVG() of the distance traveled and the SUM() of the total distance traveled can be calculated from a single query:
SUM() and AVG() aggregation queries are billed using the existing aggregations query pricing. 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.
Thanks to Chaitra Ramarao, Product Manager and Minh Nguyen, Senior Product Manager Lead for Firestore, for their contributions to this blog post.