Jump to Content
Databases

Calculate SUM and AVG aggregations using Firestore

November 7, 2023
Han Weng

Software Engineer

Matthew Tang

Software Engineer

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().

Usage

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:

lang-py
Loading...

It’s just as easy to find the average distance traveled as well:

lang-py
Loading...

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:

lang-py
Loading...

Pricing

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.

Next steps

Get started with SUM() and AVG() aggregations today by reviewing the documentation for aggregation queries for either Firestore Native Mode and Firestore in Datastore Mode.


Thanks to Chaitra Ramarao, Product Manager and Minh Nguyen, Senior Product Manager Lead for Firestore, for their contributions to this blog post.

Posted in