mongodb/how-to-query-a-random-row-using-pymongo

mongodb/how-to-query-a-random-row-using-pymongo

mongodb: How to query a random row using pymongo

  1. Get a count of every row.
  2. Create an offset in the range of 1 to count.
  3. Query for the item, skipping to the offset, limiting one result, and taking the [0]th index.

.. code-block:: python

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 }