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

.. raw:: html

   <table class="provenance-header" style="border: 0; border-collapse: collapse; margin: 0 0 16px 0; width: 100%;">

.. raw:: html

   <tr style="border: 0;">

.. raw:: html

   <td style="border: 0; vertical-align: top; padding: 0 24px 0 0;">

..

   | **Source:**
     https://foxhop.net/f3466a67-2f95-11f1-8e6a-e86a64d24d78/mongodb-how-to-query-a-random-row-using-pymongo
   | **Snapshot:** 2026-10-16T05:44:42Z
   | **Generator:** Remarkbox ``d747782``

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

.. raw:: html

   </td>

.. raw:: html

   <td style="border: 0; vertical-align: top; width: 200px; text-align: right;">

.. figure:: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAALQAAAC0AQAAAAAVtjufAAABuElEQVR42tWYQW4DUQhDUS/A/W/pG1CemVZdZBPJXWSUiSZ/4c/H2DCpeXmpPma9qnq6NSWp+hb0Va+vd9dreviUN/BPFpL41b3wG3SrpT0KT1n8hQV5d2nNP+DvFw9PfsL4A7rKCfpZCOIb+O8Vrh+XaV/9wMItBPOjRRcC2bMArSy+bxO84bPHshDldzOOxMwDIl6us/GLa3fY6HeHJaOz+K7LFW+dQyzNyfzAZ3EI7yA/JeMX7ol48dA+OqLxc4LLz6ZHZxXR+re2bKGbHk6hKL8LOM59ywozFUF8UT0gE7jLs7P1g0PgmoJitsr6A36Pv7nJnAyy/jy0X3M8NPrO4mM9tBhqlBxtjUbrB2kBiy/8tpskPkkH2+MDyR9l+/u4QKvsodfEsv5G3KgMcVln0foZ0NvTSeFyYfx+WuO1YHpxVl9jW/MW9gnCz/Kr1qkMk7g7Ov+Qb0god7Jziej8gCeALU8QnnKz8xuaooZM8GT163FTF7jscJ2dD8evFLICdL0+/n7BzNZnnW71YXx7AtpCbPbTcPx4Jt5Gi0/7w9NhzkLPT8Pzed+I604vsxyu/8/9f+AbuJ5PpV9HVrwAAAAASUVORK5CYII=
   :alt: Scan for living source

   Scan for living source

.. raw:: html

   </td>

.. raw:: html

   </tr>

.. raw:: html

   </table>

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.

.. container::
   :name: cb1

   ::

      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-10-16T05:44:42Z
| **Generator:** Remarkbox ``d747782``
