Skip to content

Instantly share code, notes, and snippets.

@89465127
Created May 13, 2013 19:39
Show Gist options
  • Save 89465127/5570881 to your computer and use it in GitHub Desktop.
Save 89465127/5570881 to your computer and use it in GitHub Desktop.
Pymongo implementation as described here: http://cookbook.mongodb.org/patterns/random-attribute/ Note that you need to have the field 'random' indexed in mongo: http://api.mongodb.org/python/current/api/pymongo/collection.html#pymongo.collection.Collection.ensure_index Could be extended to use other formal parameters from find: http://api.mongod…
def get_random(collection, query={}):
'''Gets a random record from a mongo collection'''
random_num = random.random()
query.update({'random' : {'$gte' : random_num}})
result = collection.find_one(query)
if not result:
query.update({'random' : {'$lt' : random_num}})
result = collection.find_one(query)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment