Firestore: How to get random documents in a collection

后端 未结 8 1712
旧巷少年郎
旧巷少年郎 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:22

    For those using Angular + Firestore, building on @Dan McGrath techniques, here is the code snippet.

    Below code snippet returns 1 document.

      getDocumentRandomlyParent(): Observable {
        return this.getDocumentRandomlyChild()
          .pipe(
            expand((document: any) => document === null ? this.getDocumentRandomlyChild() : EMPTY),
          );
      }
    
      getDocumentRandomlyChild(): Observable {
          const random = this.afs.createId();
          return this.afs
            .collection('my_collection', ref =>
              ref
                .where('random_identifier', '>', random)
                .limit(1))
            .valueChanges()
            .pipe(
              map((documentArray: any[]) => {
                if (documentArray && documentArray.length) {
                  return documentArray[0];
                } else {
                  return null;
                }
              }),
            );
      }
    

    1) .expand() is a rxjs operation for recursion to ensure we definitely get a document from the random selection.

    2) For recursion to work as expected we need to have 2 separate functions.

    3) We use EMPTY to terminate .expand() operator.

    import { Observable, EMPTY } from 'rxjs';
    

提交回复
热议问题