G
G
Georg2012-04-29 00:21:54
PHP
Georg, 2012-04-29 00:21:54

How to choose a random document

Good evening.
How to select a random document from a MongoDB collection?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
ertaquo, 2012-04-29
@ertaquo

Here is a similar question with multiple answers: Random record from MongoDB .
To recap the option that got the most votes there: find the number of entries in the collection and skip yourRandomNumber = (int)(rand() * count) entries:

db.yourCollection.find().limit(-1).skip(yourRandomNumber).next()

A
avalak, 2012-04-29
@avalak

In The MongoDB Cookbook, this is The Random Attribute .

E
egorinsk, 2012-04-30
@egorinsk

Do documents have integer sequential id's? Here, in Mysql in PHP, this is easily solved: we get max_id and min_id, generate 20 random numbers in this range and select SELECT * FROM table WHERE id IN (20 random numbers) LIMIT 1. It works great, through indexes, without any perversions.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question