如何在 swift for firebase 中使用 sum() 聚合?

问题描述 投票:0回答:1

我需要按照here的描述快速获取firebase中sessions集合中所有totalTime: Int值的总和,但是我不知道如何做到这一点,并且在文档中找不到它:

   func sumTotalTime() async throws -> Int {
        guard let uid = self.userSession?.uid else {
            print("User not authenticated.")
            return 0
        }
        var sum = 0
        let query = db.collection("users/\(uid)/sessions")
        let sumQuery = query.aggregate([.sum("totalTime")])
        do {
          let snapshot = try await sumQuery.getAggregation(source: .server)
            print("this is the sum of all time", snapshot)
//            sum = ??
        } catch {
          print(error)
        }
        return sum
    }

此代码似乎返回快照中的某些内容,但我不确定如何使用它,或者它是否包含正确的数据。你会如何解决这个问题?

swift database firebase google-cloud-firestore aggregate
1个回答
0
投票

不知何故,移动 SDK 的求和和平均函数还没有代码示例(我正在四处询问),但这里有一个来自 单元测试 的示例:

func testAverageUnderflow() async throws {
 let collection = collectionRef()
 try await collection.addDocument(data: ["underflowSmall": Double.leastNonzeroMagnitude])
 try await collection.addDocument(data: ["underflowSmall": 0])

 let snapshot = try await collection.aggregate([AggregateField.average("underflowSmall")])
   .getAggregation(source: .server)

 // Average
 XCTAssertEqual(snapshot.get(AggregateField.average("underflowSmall")) as? Double, 0.0)
}

所以看起来你可以通过以下方式从快照中获取总和:

snapshot.get(AggregateField.sum("totalTime"))
© www.soinside.com 2019 - 2024. All rights reserved.