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

查看:18
本文介绍了如何在 Cloud 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".

集合名称:积分

  • document1: {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.

更好的方法是在您的数据库中保留一个所谓的运行总计,每当将文档写入(添加、修改、删除)到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天全站免登陆