Search code examples
swiftdatabasefirebasegoogle-cloud-firestoreaggregate

How do you use the sum() aggregation in swift for firebase?


I need to get the sum of all the totalTime: Int values in the sessions collection in firebase with swift as described here, however I am not sure how to do it and I can't find it in the documentation:

   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
    }

This code appears to return something in the snapshot, but I am not sure how to use it or if it's even got the right data in it. How would you resolve this?


Solution

  • Somehow there are no code samples for the sum and average functions for the mobile SDKs yet (I'm asking around for them), but here's an example from the unit tests:

    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)
    }
    

    So it looks like you can get the sum from the snapshot with something like:

    snapshot.get(AggregateField.sum("totalTime"))