1

I have a Firebase query:

Firestore.firestore().collection("users")
            .whereField("activated", isEqualTo: 1)
            .whereField("gender", isEqualTo: gender == 1 ? 0 : 1)
            .order(by: "createdAt", descending: true)
            .limit(to: 5)
            .getDocuments{(snapshot, error) in
            guard let snap = snapshot else {
                print("error fetching data")
                return
            }
            var users = [User]()
            for document in snap.documents {
                let dict = document.data()
                guard let decodedUser = try? User.init(fromDictionary: dict) else { return }
                if Auth.auth().currentUser!.uid != decodedUser.uid {
                    if decodedUser.profileURL != "" {
                        users.append(decodedUser)
                    }
                }
            }
            self.allUsers = users
            self.showLoadingIndicator = false
        }

Does firebase allow you to bring back random data.

For example at the moment im getting back 5 of the latest users:

.order(by: "createdAt", descending: true)
.limit(to: 5)

I wanted to bring back 20 user and then only display a random 5 out of the 20.

Gurmukh Singh
  • 1,875
  • 3
  • 24
  • 62

1 Answers1

1

If you want to fetch 20 documents then just set .limit(to: 20) and then choose any 5 yourself using Swift. snap.documents is an array of FIRDocumentSnapshots so you can write a function that randomly selects any 5 items and then display them.

Checkout Get random elements from array in Swift

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84