14y, 313d ago
[edited]
mongodb: How to
query a random row using pymongo
- Get a count of every row.
- Create an offset in the range of 1 to count.
- Query for the item, skipping to the offset, limiting one result, and
taking the [0]th index.
def getone( request ):
id = request.matchdict[ 'id' ]
if id == 'random':
from random import randrange
count = request.db['people'].count()
offset = randrange( 1, count )
person = request.db['people'].find().skip( offset ).limit(1)[0]
else:
person = request.db['people'].find_one( { 'id': int(id) } )
return { 'person': person }
Comments