In MySQL, five random records can be simply obtained by the following statement:

SELECT * FROM `table` ORDER BY RAND() LIMIT 5

But under MongoDB, it was not found`rand()`

Methods, and`ObjectID`

Also not MySQL integer, not random, I do not know what you have a good way?

In fact, there are discussions on whether to add this feature:https://jira.mongodb.org/browse/SERVE …At present there seems to be no real progress.

In fact, MySQL only creates a temporary table, generates a random number for all the alternative rows, and then sorts the random number to get the results you need.

In MongoDB, you have to build this sort attribute for doc. The value of this attribute can be a random number fromcookbookIn the pick from:

db.docs.save( { key : 1, ..., random : Math.random() } )When searching, also calculate a random number, and then go to the sorting attribute to find the closest to it, but remember to index the sorting attribute:

rand = Math.random() cmp = Math.random() result = db.docs.findOne( { key : 2, random : { $gte : rand } } ) if ( result == null ) { result = db.docs.findOne( { key : 2, random : { $lte : rand } } ) }Because the value of the sort attribute is not dynamic as in MySQL, if you want to get multiple DOCs at random, you have to loop the above operations.

I think the root of this problem is whether random in mathematical sense is needed. If only a rough idea is needed, Map/Reduce can be used to improve convergence speed for large data volumes without indexing.

So, in fact, time stamps can be used. Any attribute that can find the upper and lower limit values and not too many duplicate values can be used for random sorting.