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

Swift应用中Firestore使用count聚合获取未读通知数的实现疑问

问题:使用Firestore聚合count获取未读通知数量的实现

原本使用以下fetch()函数从Firestore获取当前用户的未读通知(read字段值为"n"),并映射为Notification对象列表:

func fetch() async throws {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let snapshot = try await  Firestore.firestore().collection("notifications").document(uid).collection("user-notifications")
        .whereField("read", isEqualTo: "n")
        .limit(to: 10)
        .getDocuments()
    self.notifications = try snapshot.documents.compactMap({ try $0.data(as: Notification.self) })
}

现在想要切换到fetch2()函数,使用Firestore的count聚合仅获取未读通知的数量,但不清楚如何替换原fetch()中self.notifications = try snapshot.documents.compactMap({ try $0.data(as: Notification.self) })这部分代码:

func fetch2() async throws {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let query = Firestore.firestore().collection("notifications").document(uid).collection("user-notifications")
        .whereField("read", isEqualTo: "n")
        .limit(to: 10)
    let countQuery = query.count
    let snapshot = try await countQuery.getAggregation(source: .server)
}

请问该如何实现这部分代码的替换?


解决方案

Firestore聚合查询返回的AggregationSnapshot对象直接包含计数结果,你可以通过snapshot.count属性获取未读通知数量,赋值给对应的存储属性即可:

完整的fetch2()实现

// 先在类中定义存储数量的属性
var unreadNotificationCount: Int64 = 0

func fetch2() async throws {
    guard let uid = Auth.auth().currentUser?.uid else { return }
    let query = Firestore.firestore().collection("notifications").document(uid).collection("user-notifications")
        .whereField("read", isEqualTo: "n")
        .limit(to: 10)
    let countQuery = query.count
    let snapshot = try await countQuery.getAggregation(source: .server)
    
    // 替换原赋值逻辑,直接获取count值
    self.unreadNotificationCount = snapshot.count
}

补充说明

  • snapshot.count的类型是Int64,所以存储属性建议定义为Int64;如果需要转为Int,可以用Int(snapshot.count),注意数值溢出风险。
  • 原查询中的limit(to:10)会限制计数上限为10,即未读通知超过10条时,返回的count值为10,和原逻辑保持一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 04:43:32