Firebase汇总属性的值,而无需获取所有相关文档 [英] Firebase aggregate values over property without fetching all relevant documents

查看:64
本文介绍了Firebase汇总属性的值,而无需获取所有相关文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下firebase结构:

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
            }
        }
    }   
}

是说: 我有一个集合companies. 每个公司都有一个文件. 每个公司都有一个子集合invoices.

That is to say: I have a collection companies. There is a document for each company. Each company has a subcollection invoices.

每个发票都具有属性amountcurrencytimestamp.

Each invoice has the properties amount,currency,timestamp.

是否存在一种有效的方法来获取公司所有发票的总金额,而无需从Firestore提取所有相关文档? 这是我想出的方法,效率很低:

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.

推荐答案

是否有一种有效的方法来获取公司所有发票的总金额,而无需从Firestore中获取所有相关文档?

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?

是的,您可以在名为totalAmount的公司文档中添加新属性,您可以在其中存储所有发票的总额.每次添加新发票时,只需将totalAmount随新发票的金额增加即可.现在,为了获得此新属性的值,需要读取单个文档.使用此解决方案,您只需支付一项读取操作,而无需 支付您的发票子集合中的发票总数.

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.

这篇关于Firebase汇总属性的值,而无需获取所有相关文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆