How does MongoDB get several records randomly

  mongodb, question

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


But under MongoDB, it was not foundrand()Methods, andObjectIDAlso 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: …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: { 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 = { key : 2, random : { $gte : rand } } )
if ( result == null ) {
    result = { 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.