October 2023 update
With Firebase JS SDK 10.5.0 released on October 12th 2023, Cloud Firestore now supports sum
and average
aggregations queries.
I recommend you check the aggregation query documentation for more information.
Using the sum()
function with the Web v9 SDK
Assuming you want to sum all the scores in the points
collection:
const coll = collection(firestore, 'points');
const snapshot = await getAggregateFromServer(coll, {
totalScores: sum('value')
});
console.log('totalScores: ', snapshot.data().totalScores);
Assuming you want to sum the scores of one particular user
:
const coll = collection(firestore, 'points');
const q = query(coll, where('userid', '==', user.id));
const snapshot = await getAggregateFromServer(q, {
totalUserScore: sum('value')
});
console.log('totalUserScore: ', snapshot.data().totalUserScore);
Note: Don't forget to import from firestore the functions used in the above examples. That includes collection
, getAggregateFromServer
, sum
, query
and where
.
Be aware of the following limitations when using the sum()
function (included here in the documentation)
For sum()
and average()
aggregations, non-numeric values are ignored. sum()
and average()
aggregations take into account only
integer values and floating-point number values.
When combining multiple aggregations in a single query, note that sum()
and average()
ignore non-numeric values while count()
includes
non-numeric values.