Firebase aggregate values over property without fetching all relevant documents

我们两清 提交于 2020-01-21 18:36:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!