我需要按照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
}
此代码似乎返回快照中的某些内容,但我不确定如何使用它,或者它是否包含正确的数据。你会如何解决这个问题?
不知何故,移动 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"))