Random record from MongoDB

后端 未结 27 2522
栀梦
栀梦 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:51

    What works efficiently and reliably is this:

    Add a field called "random" to each document and assign a random value to it, add an index for the random field and proceed as follows:

    Let's assume we have a collection of web links called "links" and we want a random link from it:

    link = db.links.find().sort({random: 1}).limit(1)[0]
    

    To ensure the same link won't pop up a second time, update its random field with a new random number:

    db.links.update({random: Math.random()}, link)
    

提交回复
热议问题