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

如何使用C#从Firestore中列出文档并获取用户设备名称

遍历Firestore Users集合所有文档并获取Device Name字段

问题场景

我有一个名为Users的Collection,当前包含A、B两个Document,后续可能新增更多用户。需要列出所有Document并获取每个用户的Device Name字段值,但当前代码只能获取指定的Document:

DocumentReference documentRef = db.Collection("User").Document("A");
DocumentReference documentRef2 = db.Collection("User").Document("B");
DocumentSnapshot documentSnapshot = await documentRef.GetSnapshotAsync();
DocumentSnapshot documentSnapshot2 = await documentRef2.GetSnapshotAsync();
if (documentSnapshot.Exists && documentSnapshot2.Exists)
{
    string deviceName = documentSnapshot.GetValue<string>("Device Name");
    string deviceName2 = documentSnapshot2.GetValue<string>("Device Name");
    MessageBox.Show($"Device Name: {deviceName}");
    MessageBox.Show($"Device Name 2: {deviceName2}");
}
else
{
    MessageBox.Show("Document does not exist.");
}

解决方案

要动态获取集合下所有文档,无需硬编码文档ID,直接对集合调用查询接口即可:

// 获取Users集合的引用(统一集合名为Users,与描述一致)
CollectionReference usersRef = db.Collection("Users");
// 获取集合内所有文档的快照
QuerySnapshot querySnapshot = await usersRef.GetSnapshotAsync();

// 遍历每个文档处理
foreach (DocumentSnapshot docSnapshot in querySnapshot.Documents)
{
    if (docSnapshot.Exists)
    {
        // 安全获取Device Name字段(避免字段不存在报错)
        if (docSnapshot.TryGetValue<string>("Device Name", out string deviceName))
        {
            MessageBox.Show($"用户 {docSnapshot.Id} 的Device Name: {deviceName}");
        }
        else
        {
            MessageBox.Show($"用户 {docSnapshot.Id} 未配置Device Name字段");
        }
    }
    else
    {
        MessageBox.Show($"文档 {docSnapshot.Id} 不存在");
    }
}

关键说明

  • 直接调用集合的GetSnapshotAsync(),一次性获取所有文档的快照,自动适配后续新增的用户文档
  • 使用foreach遍历querySnapshot.Documents,逐个处理每个文档
  • 用TryGetValue替代GetValue,避免因部分文档缺少Device Name字段导致程序异常
  • 通过docSnapshot.Id可以获取每个文档的标识(即原代码中的A、B等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:50:11