Unity C#中获取Firestore文档总数及按学校筛选取姓名方法
Unity C#操作Firestore实现指定需求
1. 获取"users"集合的文档总数
Firestore没有直接返回集合总数的API,可根据数据量选择以下两种方案:
方案一:小数据量场景(直接拉取计数)
适合文档数量较少的集合,直接获取快照后统计总数:
using Firebase.Firestore; using UnityEngine; public class FirestoreHandler : MonoBehaviour { private async void GetUsersTotalCount() { Firestore db = FirebaseFirestore.DefaultInstance; var usersCollection = db.Collection("users"); try { QuerySnapshot snapshot = await usersCollection.GetSnapshotAsync(); int total = snapshot.Documents.Count; Debug.Log($"users集合文档总数:{total}"); } catch (System.Exception e) { Debug.LogError($"获取计数失败:{e.Message}"); } } }
方案二:大数据量场景(聚合查询)
文档数量较多时,用聚合查询避免拉取全部数据,提升效率:
using Firebase.Firestore; using UnityEngine; public class FirestoreHandler : MonoBehaviour { private async void GetUsersCountWithAggregation() { Firestore db = FirebaseFirestore.DefaultInstance; var usersCollection = db.Collection("users"); try { AggregateQuerySnapshot aggSnapshot = await usersCollection.Count().GetSnapshotAsync(); long total = aggSnapshot.Count; Debug.Log($"users集合文档总数:{total}"); } catch (System.Exception e) { Debug.LogError($"聚合查询计数失败:{e.Message}"); } } }
2. 按"school"字段筛选并获取对应人员姓名
使用WhereEqualTo筛选指定学校的文档,遍历提取姓名字段:
using Firebase.Firestore; using UnityEngine; using System.Collections.Generic; public class FirestoreHandler : MonoBehaviour { private async void FetchUsersBySchool(string targetSchool) { Firestore db = FirebaseFirestore.DefaultInstance; var usersCollection = db.Collection("users"); try { Query filteredQuery = usersCollection.WhereEqualTo("school", targetSchool); QuerySnapshot snapshot = await filteredQuery.GetSnapshotAsync(); List<string> userNames = new List<string>(); foreach (DocumentSnapshot doc in snapshot.Documents) { if (doc.Exists) { string name = doc.GetValue<string>("name"); if (!string.IsNullOrEmpty(name)) { userNames.Add(name); } } } Debug.Log($"[{targetSchool}] 人员名单:"); foreach (string name in userNames) { Debug.Log(name); } } catch (System.Exception e) { Debug.LogError($"筛选数据失败:{e.Message}"); } } }
注意事项
- 确保Unity项目已正确集成Firebase SDK并完成Firestore初始化。
- 异步方法需在支持async的上下文调用,如Unity的
async void方法或结合协程使用。 - 若需实时监听数据变化,可将
GetSnapshotAsync替换为Listen方法。
内容的提问来源于stack exchange,提问作者Savad
相关产品推荐
相关产品推荐

