Random record from MongoDB

后端 未结 27 1988
栀梦
栀梦 2020-11-22 01:22

I am looking to get a random record from a huge (100 million record) mongodb.

What is the fastest and most efficient way to do so? The data is already t

27条回答
  •  無奈伤痛
    2020-11-22 01:53

    You can pick random _id and return corresponding object:

     db.collection.count( function(err, count){
            db.collection.distinct( "_id" , function( err, result) {
                if (err)
                    res.send(err)
                var randomId = result[Math.floor(Math.random() * (count-1))]
                db.collection.findOne( { _id: randomId } , function( err, result) {
                    if (err)
                        res.send(err)
                    console.log(result)
                })
            })
        })
    

    Here you dont need to spend space on storing random numbers in collection.

提交回复
热议问题