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

JSON

rev 1  |  foxhop  |  1307197679000  |  JSON

empty
rev 1
tt1mongodb: How to query a random row using pymongo
2=======================================================
3 
4#. Get a count of every row.
5#. Create an offset in the range of 1 to count.
6#. Query for the item, skipping to the offset, limiting one result, and taking t
 >he [0]th index.
7 
8.. code-block:: python
9 
10    def getone( request ):
11    id = request.matchdict[ 'id' ]
12    if id == 'random':
13        from random import randrange
14        count  = request.db['people'].count()
15        offset = randrange( 1, count )
16        person = request.db['people'].find().skip( offset ).limit(1)[0]
17    else:
18        person = request.db['people'].find_one( { 'id': int(id) } )
19 
20    return { 'person': person }