How can I get a random document from a Cloud Firestore collection without reading the whole collection?
Given a collection with tens of thousands of documents (users), I need to pick a random one (the winner).
How can I get a random document from a Cloud Firestore collection without reading the whole collection?
Given a collection with tens of thousands of documents (users), I need to pick a random one (the winner).
The simplest solution I can think of would be to store the UIDs of all users in a single document, in a field of type array. If all those UIDs don't fit into a single document, due to the 1 MiB limitation, then store them in two documents, or even three if necessary. Read those documents, and pick a random UID. In this way, you'll avoid reading tens of thousands of documents, so you'll end up reading only a few. Duplicating data (UIDs) is a quite common practice when it comes to NoSQL databases.
Besides that, don't also forget to update the arrays frequently, meaning if a new user joins your app, add the UID to the array, and if a user leaves your app, delete the UID from the array.