Is there any standard firestore query to get random documents?

Viewed 1409

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.

1 Answers

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.

Related