Select random document from Firestore

后端 未结 5 1581
囚心锁ツ
囚心锁ツ 2020-11-27 07:40

I have 1000 documents in a single collection in Cloud Firestore, is it possible to fetch random documents?

Say for example: Students is a collection in

5条回答
  •  眼角桃花
    2020-11-27 08:18

    Based on @ajzbc answer I wrote this for Unity3D and its working for me.

    FirebaseFirestore db;
    
        void Start()
        {
            db = FirebaseFirestore.DefaultInstance;
        }
    
        public void GetRandomDocument()
        {
    
           Query query1 = db.Collection("Sports").WhereGreaterThanOrEqualTo(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
           Query query2 = db.Collection("Sports").WhereLessThan(FieldPath.DocumentId, db.Collection("Sports").Document().Id).Limit(1);
    
            query1.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask1) =>
            {
    
                 if(querySnapshotTask1.Result.Count > 0)
                 {
                     foreach (DocumentSnapshot documentSnapshot in querySnapshotTask1.Result.Documents)
                     {
                         Debug.Log("Random ID: "+documentSnapshot.Id);
                     }
                 } else
                 {
                    query2.GetSnapshotAsync().ContinueWithOnMainThread((querySnapshotTask2) =>
                    {
    
                        foreach (DocumentSnapshot documentSnapshot in querySnapshotTask2.Result.Documents)
                        {
                            Debug.Log("Random ID: " + documentSnapshot.Id);
                        }
    
                    });
                 }
            });
        }
    

提交回复
热议问题