如何读取Firestore文档中指定的单个字段数据?
Firestore 读取单个指定字段的实现方法
Firestore 支持在请求阶段就指定仅返回需要的字段,避免拉取整个文档的冗余数据,针对你使用的 Swift 客户端,实现方式如下:
方法1:请求时仅拉取指定字段(推荐)
使用 select(_ fields: [String]) 方法在服务端就过滤返回内容,仅返回你需要的字段,降低传输带宽消耗:
db.collection("users").document("\(username)").select(["league"]).getDocument { (document, error) in if let document = document, document.exists { // 直接读取指定字段值 let league = document.get("league") as? String ?? "未获取到段位信息" print("当前段位:\(league)") } else { print("文档不存在或读取错误:\(error?.localizedDescription ?? "未知错误")") } }
如果需要同时拉取多个指定字段,在 select 的数组中添加对应的字段名即可,例如 select(["league", "Total calories burnt"])
方法2:全量拉取后提取指定字段
如果你的场景允许拉取全量文档,也可以直接从返回的文档快照中提取单个字段:
db.collection("users").document("\(username)").getDocument { (document, error) in if let document = document, document.exists { let league = document.data()?["league"] as? String ?? "未获取到段位信息" // 也可以用更简便的get方法:let league = document.get("league") as? String print("当前段位:\(league)") } else { print("文档读取失败:\(error?.localizedDescription ?? "未知错误")") } }
注意:使用
select方法仅会改变返回的字段内容,计费仍然按照1次文档读操作计算,不会减少读请求的计费次数。
内容的提问来源于stack exchange,提问作者Kiran Lim
相关产品推荐
相关产品推荐

