Home > Software engineering >  Iterate through all documents and sum a field - Firebase
Iterate through all documents and sum a field - Firebase

Time:10-05

I have iterated through all documents of specific collection and made the sum of specific property/field to get the total amount, I able to did it but the problem is that this method is not effective in terms of performance and cost performance because firebase charges according to the usage (read/write document)

So what could be the better approach to do it?

here is my code

basically there is an sub collection called 'userEntries' and it has lots of document and each document has a field called 'amount'

  double totalAmount = 0;

  void getTotalAmount() async {
    QuerySnapshot customerEntries = await FirebaseFirestore.instance.collection('entries').doc(widget.firebaseUser!.uid).collection('userEntries').where('customerId', isEqualTo: widget.customerMap['customerId']).get();
    double total = 0;
    for (var element in customerEntries.docs) {
        total  = element['amount'];
    }

    setState(() {
      totalAmount = total;
    });
  }

What I can think of is maintain a separate sub collection where I would write/update totalAmount field whenever a user would make a new entry, is it right way to do it?

CodePudding user response:

What I can think of is maintain a separate sub collection where I would write/update totalAmount field whenever a user would make a new entry, is it right way to do it?

Yes, this is the right way to do that. There is a specific page in the Firestore documentation which explains how to do that with several documents in order to solve the maximum limit of one write to a document per second.

The code examples in this page do not show the Dart version but it is easy to implement it based on the JS example.

  • Related