You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Firebase Security Rules中计算Firestore映射的value总和?

计算Firestore中ratings映射的value总和

Web(JavaScript)

假设已获取到包含ratings的文档快照,可通过以下方式计算总和:

// 从文档快照中取出数据
const docData = docSnapshot.data();
const ratings = docData.ratings;

// 用reduce简洁计算总和
const total = Object.values(ratings).reduce((sum, item) => sum + (item.value || 0), 0);
console.log('总和:', total); // 输出示例中的8

也可以用循环遍历的方式:

let total = 0;
for (const key in ratings) {
  if (ratings.hasOwnProperty(key)) {
    total += ratings[key].value || 0; // 空值处理避免报错
  }
}

Android(Kotlin)

若在Android端开发,可参考以下代码:

// 假设doc是获取到的DocumentSnapshot
val ratings = doc.get("ratings") as? Map<String, Map<String, Any>> ?: emptyMap()
var total = 0.0

for ((_, rating) in ratings) {
  val value = rating["value"] as? Number
  value?.let { total += it.toDouble() }
}

Log.d("Total", "总和: $total")

iOS(Swift)

iOS端Swift实现示例:

// 假设document是获取到的DocumentSnapshot
guard let ratings = document.data()?["ratings"] as? [String: [String: Any]] else { return }
var total = 0.0

for (_, rating) in ratings {
  if let value = rating["value"] as? Double {
    total += value
  }
}

print("总和: \(total)")

注意事项

  • 若存在部分rating对象缺失value字段的情况,务必做空值判断,避免程序报错。
  • 可根据实际数据类型调整数值类型(比如用Int代替Double)。

内容的提问来源于stack exchange,提问作者asd man

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 00:15:36