Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Implement SUM() function of SQL in cloud Firestore

I am storing scores of a user in google cloud firestore as each score a new document in the collection named as "points".

collection name: points

  • document1: {id:111,userid:345,value:50}
  • document2:{id:222,userid:345,value:70}
  • document3:{id:333,userid:345,value:30}
  • document1:{id:444,userid:345,value:100}

I want to sum all values in value field.

I have google many times but found nothing. Is there any alternative for sum() or any other way to implement recording scores of a user?

like image 777
Jaspal Avatar asked Jan 19 '18 11:01

Jaspal


1 Answers

There are no built-in aggregation operators in Cloud Firestore.

The naïve solution is to load the data in the client and sum it there, but that means that you (and your users) incur the cost of loading all documents for each time they need to show the sum.

A better way is to keep a so-called running total in your database, which you update whenever a document is written to (added, modified, removed) to the "points" collection. For this you have two options: do it from the client, or do it from a trusted environment (such as Cloud Functions). The Firestore documentation on aggregation queries describes both options and shows sample code.

like image 164
Frank van Puffelen Avatar answered Oct 07 '22 17:10

Frank van Puffelen