Ordering a result set randomly in mongo

前端 未结 6 837
终归单人心
终归单人心 2020-12-09 17:36

I\'ve recently discovered that Mongo has no SQL equivalent to \"ORDER BY RAND()\" in it\'s command syntax (https://jira.mongodb.org/browse/SERVER-533)

I\'ve seen the

6条回答
  •  一生所求
    2020-12-09 17:49

    One could insert an id field (the $id field won't work because its not an actual number) use modulus math to get a random skip. If you have 10,000 records and you wanted 10 results you could pick a modulus between 1 and 1000 randomly sucH as 253 and then request where mod(id,253)=0 and this is reasonably fast if id is indexed. Then randomly sort client side those 10 results. Sure they are evenly spaced out instead of truly random, but it close to what is desired.

提交回复
热议问题