Created
May 13, 2013 19:39
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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