skip to Main Content

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 total scores of a user?
Can someone give pointers right now I can only see support for NodeJS, Java and Web Modular Api

2

Answers


  1. You have to loop through your items in a collection and add the value. Something like this:

    int total = 0;
    void getData() {
      databaseReference
          .collection("points")
          .getDocuments()
          .then((QuerySnapshot snapshot) {
        snapshot.documents.forEach((f) => total += f.value);
      });
    }
    

    P.S. please always post your workings or your code when you ask a question.

    Login or Signup to reply.
  2. The sum and average aggregation operators for Firestore in Flutter are still in progress. Work on it has started, but it hasn’t been completed yet.

    Surprisingly, there was no feature request on the github repo for this yet – so I just added #12074. I recommend checking there for the latest status, and keeping an eye on the FlutterFire changelog.


    Until the feature lands, your only option is to load the documents and sum the values client-side as @MdKamrulAmin explains in their answer or to use a write-time aggregation.


    Also see my explanation on the various options for aggregations in How should I handle aggregated values in Firestore

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search