Hitul Mistry Hitul Mistry - 2 years ago 175
Python Question

How to get random single document from 1 billion documents in mongoDB using python?

I want single random document from mongoDB collection. Now my mongoDB collection contains more then 1 billion collections. How to get single random document from that collection ?

Answer Source

Add an additional column named random to your collection and make that the value in it is between 0 to 1. You can assign random floating points between 0 to 1 into this column for each record via [random.random() for _ in range(0, 10)].


import random

collection = mongodb["collection_name"]

rand = random.random()  # rand will be a floating point between 0 to 1.
random_record = collection.find_one({ 'random' => { '$gte' => rand } })

MongoDB will have its native implementation in due course. Filed feature here - https://jira.mongodb.org/browse/SERVER-533

Not yet implemented at time of writing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download