如何在Cloud Firestore中实现SQL的SUM()函数 [英] How to Implement SUM() function of SQL in cloud Firestore

查看:98
本文介绍了如何在Cloud Firestore中实现SQL的SUM()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将用户的分数存储在Google Cloud Firestore中,因为每个分数在集合中名为""的新文档中都得分.

I am storing scores of a user in google cloud firestore as each score a new document in the collection named as "points".

集合名称:点

  • document1:{id:111,userid:345,value:50}
  • document2:{id:222,userid:345,value:70}
  • document3:{id:333,用户ID:345,值:30}
  • document1:{id:444,用户ID:345,值:100}

我想对 value 字段中的所有值求和.

I want to sum all values in value field.

我有很多次Google,但一无所获. sum()是否有其他选择或实现用户记录分数的任何其他方法?

I have google many times but found nothing. Is there any alternative for sum() or any other way to implement recording scores of a user?

推荐答案

Cloud Firestore中没有内置的聚合运算符.

There are no built-in aggregation operators in Cloud Firestore.

幼稚的解决方案是将数据加载到客户端中并在客户端进行汇总,但这意味着您(和您的用户)每次需要显示总和时都要承担加载所有文档的费用.

The naïve solution is to load the data in the client and sum it there, but that means that you (and your users) incur the cost of loading all documents for each time they need to show the sum.

一种更好的方法是在数据库中保留一个所谓的运行总计,每当将文档写入(添加,修改,删除)到"points"集合时就更新该总计.为此,您有两个选择:从客户端执行此操作,或从受信任的环境(例如Cloud Functions)执行操作. 有关聚合查询的Firestore文档描述了这两个选项并显示了示例代码.

A better way is to keep a so-called running total in your database, which you update whenever a document is written to (added, modified, removed) to the "points" collection. For this you have two options: do it from the client, or do it from a trusted environment (such as Cloud Functions). The Firestore documentation on aggregation queries describes both options and shows sample code.

这篇关于如何在Cloud Firestore中实现SQL的SUM()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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