I would like to get a random set of documents from the MongoDB database. So far, after a lot of Google, I have only seen ways to get one random document or a set of documents, starting from an arbitrary skip position, but where the documents are still sequential.
I tried mongoose-simple-random, and unfortunately it does not extract the “true” random set. What he does is go to a random position, and then extract n documents from this position.
Instead, I would like to get a random set, such as MySQL, using one query (or the minimum number of queries), and I need this list to be random every time. I need this to be effective - relatively on par with such a query with MySQL. I want to reproduce the following, but in MongoDB:
SELECT * FROM products ORDER BY rand() LIMIT 50;
Is it possible? I use Mongoose, but the example with any adapter or even direct MongoDB query is cool.
I saw one method of adding a field to each document, generating a random value for each field and using {rand: {$gte:rand()}}every request that we want to randomize. But I am worried that two queries could theoretically return the same set.