Getting maximum value of a field across a collection in Firebase

Hey all,

What I’m trying to do is basically auto-generate a user id. I don’t think Firebase has something like this built-in (I want something simple, not something lengthy like a Document ID). I was wondering how I could grab the maximum value of a field from documents in a collection. I would need to look through all the documents, not just a specific one. I’ve been thinking that it might involve a for loop, but I’m not sure how I would implement it while using Firebase. I know this was confusing, so please let me know if what I’m asking for didn’t make sense. Any help is greatly appreciated!

Thank you!

For getting a unique string:

NSUID().uuidString

After this you could sub string it for however many characters you want.

I don’t understand the second half of your question

1 Like

@YourAvgCoder
As you have probably already discovered, Firestore stores data in KeyValue pairs. If you were to have a collection of, let’s say, Users with attributes of Name, Surname, age (for example) then what you will see in Firebase is an autogenerated Document ID for each user added to the database. A bit like this example:

I have a collection of users and each user entry has a unique document ID which is auto generated. attached to that document ID are the key value pairs for the details about the user: name, address, city, postcode, age

I could do a query on all the documents within the collection of users and sum up the ages and you would do that by declaring a totalAges variable and then for each user add their age to that totalAges.

This is the code I used in my case to show you an example of how you would do that:

        let db = Firestore.firestore()
        var totalAges = 0

        db.collection("users").getDocuments { (snapshot, error) in
            if let error = error {
                print(error)
                return
            } else {
                for document in snapshot!.documents {
                    let data = document.data()
                    totalAges += data["age"] as! Int
                }
            }
            DispatchQueue.main.async {
                print(totalAges)
            }
        }

In this case the totalAges printed in the console was 94 as the individual ages on the three records were 31, 26 and 37.

Hope that helps.

Chris

1 Like

Hey @MikaelaCaron and @Chris_Parker,

Thanks for the responses! I think I got it now!