Source: https://foxhop.net/f3466a67-2f95-11f1-8e6a-e86a64d24d78/mongodb-how-to-query-a-random-row-using-pymongo
Snapshot: 2026-05-25T22:22:02Z
Generator: Remarkbox 1527ef7

This is a thread snapshot. The living document lives at the source URI above — it may have been edited, extended, or replied-to since.

Scan for living source

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.
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 }

Source: https://foxhop.net/f3466a67-2f95-11f1-8e6a-e86a64d24d78/mongodb-how-to-query-a-random-row-using-pymongo
Snapshot: 2026-05-25T22:22:02Z
Generator: Remarkbox 1527ef7