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

如何创建仅允许count聚合查询的Firestore安全规则?

Firestore规则实现:仅允许指定条件的count聚合查询

需求说明

希望用户能够查询符合指定where子句的文档数量,无需借助Cloud Functions,且严格禁止用户获取文档内容。以/users/{uid}路径下的文档为例,文档结构如下:

{
  "private_data": "...",
  "group": "groupname"
}

完善后的Firestore规则

match /users/{uid} {
  // 允许用户仅读取自己的私有数据
  allow read: if request.auth != null && request.auth.uid == uid;
  
  // 允许用户查询指定分组的用户总数(仅支持count聚合)
  allow list: if 
    request.auth != null &&
    // 强制查询必须包含group字段的相等匹配条件
    request.query.where.filter != null &&
    request.query.where.filter.field == "group" &&
    request.query.where.filter.op == "==" &&
    // 限制仅为count类型的聚合查询
    request.query.aggregate == "count" &&
    // 确保不返回任何文档内容,仅返回聚合结果
    request.query.limit == 0;
}

规则条件详解

  • request.auth != null:验证用户已完成登录,未登录用户无法发起统计请求
  • request.query.where.filter相关判断:确保用户只能针对group字段做相等匹配的统计,避免无限制或非法的查询范围
  • request.query.aggregate == "count":明确只允许count聚合操作,拒绝其他类型的聚合(如sum、avg等)
  • request.query.limit == 0:Firestore聚合查询无需返回文档内容,设置limit为0可以彻底杜绝文档数据被获取的可能,同时符合规则对聚合查询的约束

示例查询代码(JavaScript)

用户需要按以下方式发起count聚合查询,才能通过规则校验:

import { getFirestore, collection, where, query, getCountFromServer } from "firebase/firestore";

const db = getFirestore();
const coll = collection(db, 'users');
const q = query(coll, where('group', '==', 'groupname'));
const snapshot = await getCountFromServer(q);

console.log(`分组用户数量:${snapshot.data().count}`);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:27:07