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

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

问题描述

我将用户的分数存储在 google cloud firestore 中,因为每个用户都会为名为points"的集合中的一个新文档评分.

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

集合名称:积分

  • 文档 1:{id:111,userid:345,value:50}
  • document2:{id:222,userid:345,value:70}
  • document3:{id:333,userid:345,value:30}
  • document1:{id:444,userid:345,value:100}

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

I want to sum all values in value field.

我谷歌了很多次,但一无所获.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.

更好的方法是在您的数据库中保留一个所谓的运行总数,每当将文档写入(添加、修改、删除)到点"集合时,您就会更新它.为此,您有两种选择:从客户端执行,或从受信任的环境(例如 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.

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

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