Firestore: How to get random documents in a collection

后端 未结 8 1802
旧巷少年郎
旧巷少年郎 2020-11-22 10:08

It is crucial for my application to be able to select multiple documents at random from a collection in firebase.

Since there is no native function built in to Fireb

8条回答
  •  轮回少年
    2020-11-22 10:40

    Ok I will post answer to this question even thou I am doing this for Android. Whenever i create a new document i initiate random number and set it to random field, so my document looks like

    "field1" : "value1"
    "field2" : "value2"
    ...
    "random" : 13442 //this is the random number i generated upon creating document
    

    When I query for random document I generate random number in same range that I used when creating document.

    private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance()
    private var usersReference = firestore.collection("users")
    
    val rnds = (0..20001).random()
    
    usersReference.whereGreaterThanOrEqualTo("random",rnds).limit(1).get().addOnSuccessListener {
      if (it.size() > 0) {
              for (doc in it) {
                   Log.d("found", doc.toString())
               }
    } else {
        usersReference.whereLessThan("random", rnds).limit(1).get().addOnSuccessListener {
              for (doc in it) {
                      Log.d("found", doc.toString())
               }
            }
    }
    }
    

提交回复
热议问题