2

I am trying to get multiple random documents from a dynamic collection. Until know, I have thought to do it using simple queries, something like this:

 Pseudocode
 
 arr = [];
 while (arr.length < 5) {
     // Start the query at a random position
     startAt = Math.random() * collection.size;
     randomDoc = await dbRef.startAt(startAt).limit(1).get( ... );
     arr.push(randomDoc);
 }

Here, firstly, I have to get the collection size, as it can be 0 or bigger. Then, select a random document using a kind of "db random pointer/index".

My question is if there is any way to get the same result but without all the loop stuff, only with the query syntax.

Thank you.

Victor Molina
  • 2,353
  • 2
  • 19
  • 49

1 Answers1

1

Clever use of startAt and limit!
As you can see in the reference, there are no built-in methods that would return random documents.

In order to avoid the loop, you can use Promise.all:

const indices = getRandomIndices(collection.size);
const docs = await Promise.all(indices.map(i => {
    return dbRef.startAt(i).limit(1).get();
}));

And for the getRandomIndices, I suggest: create an array [0, 1, 2, ...], shuffle it as describe in this SO answer, and slice its 5 first elements.

Louis Coulet
  • 3,663
  • 1
  • 21
  • 39
  • How do you get the collection size exactly? – iusting Jun 01 '22 at 21:53
  • 1
    Hi @iusting, there is no built-in way to get a collection size, but I wrote an article on how to achieve this: https://medium.com/firebase-tips-tricks/how-to-count-documents-in-firestore-a0527f792d04 – Louis Coulet Jun 02 '22 at 18:50
  • That being said, I think that keeping the size of a collection only for the purpose of picking random elements is overkill. It can be achieved in a simpler way, for example by storing a random number in every documents and querying based on this number. – Louis Coulet Jun 02 '22 at 18:52
  • Thanks for getting back! I asked because OP mentions having a dynamic collection and the `collection.size` part misleaded me at least into thinking such property exists. I love the random number suggestion! Ended up implementing it based on a Dan McGrath solution here -> https://stackoverflow.com/questions/46798981/firestore-how-to-get-random-documents-in-a-collection. – iusting Jun 06 '22 at 21:52