问题
I have the following firebase structure:
{
"company1": {
"name": "Company One",
"invoices": {
"invoice1": {
"amount": 300,
"currency": "EUR",
"timestamp": 1572608088
},
"invoice2": {
"amount": 460,
"currency": "EUR",
"timestamp": 1572608088
}
}
}
}
That is to say:
I have a collection companies.
There is a document for each company.
Each company has a subcollection invoices.
Each invoice has the properties amount,currency,timestamp.
Is there an efficient way of getting the sum of all amounts of invoices of a company without the need to fetch all relevant documents from firestore? This would be the approach I came up with which would be rather inefficient:
this.afs.collection('companies').document('company1').collection('invoices', ref => ref.where('timestamp', '>', 1556710488).where('timestamp', '>', 1572953978))
I cannot just use a cloud function to increment a value as the requested time period is not known.
回答1:
Is there an efficient way of getting the sum of all amounts of invoices of a company without the need to fetch all relevant documents from Firestore?
Yes, you can add a new property in your company document named totalAmount, where you can store the total amount of all your invoices. Every time you add a new invoice, simply increment the totalAmount with the amount of the new invoice. Now in order to get the value of this new property a single document read is needed. Using this solution, you'll be charged with only one read operation and not with the total number of invoices that you have in your invoices subcollection.
来源:https://stackoverflow.com/questions/58710688/firebase-aggregate-values-over-property-without-fetching-all-relevant-documents