search

Home  >  Q&A  >  body text

nosql - MongoDB如何随机获取若干条记录

在MySQL中,可以通过下面的语句简单的获取随机的5条记录:

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

但是在MongoDB下,没有找到rand()方法,而且ObjectID也不是MySQL那样整数的,不好随机,不知道大家有什么好办法?

黄舟黄舟2799 days ago711

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-21 10:58:15

    There is actually discussion on whether to add this feature: https://jira.mongodb.org/browse/SERVE..., but there seems to be no substantial progress at present.

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

    In MongoDB, you have to build such a sorting attribute for doc yourself. The value of this attribute can be a random number, taken from the cookbook:

    db.docs.save( { key : 1, ..., random : Math.random() } )

    When searching, calculate a random number, and then find the one closest to it in the sorting attribute, but remember to add an index to 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 sorting attribute is not dynamic like in MySQL, if you want to obtain multiple docs truly randomly, you have to loop the above operation.

    I think the root of this problem is whether randomness in the mathematical sense is needed. If you just want a rough idea, for large amounts of data without indexing, you can use Map/Reduce to improve the convergence speed.

    So, in fact, timestamps can also be used. Any attribute that can find the upper and lower limit values ​​without too many repeated values ​​can be used for random sorting.

    reply
    0
  • ringa_lee

    ringa_lee2017-04-21 10:58:15

    Add conditions
    "$where":function () { if(Math.random()>0.1){return true;}else{return false;}}
    In conjunction with limit(1)
    Randomly select a record from the set with a probability of 1/10
    It may be easier, but its application is more limited. For reference only~

    reply
    0
  • Cancelreply