Random Document Selector for MongoDB

  • Share this:

Code introduction


This function randomly selects a document from a MongoDB collection. It first connects to MongoDB, then counts the number of documents in the collection, randomly selects an offset, uses a cursor to jump to that position, and returns the document at that position.


Technology Stack : MongoDB, pymongo

Code Type : Function

Code Difficulty : Intermediate


                
                    
def find_random_document(collection, filter={}):
    import random
    from pymongo import MongoClient, ASCENDING
    
    client = MongoClient('mongodb://localhost:27017/')
    db = client['mydatabase']
    cursor = collection.find().sort('_id', ASCENDING)
    
    # Skip to a random document
    count = collection.count_documents(filter)
    random_offset = random.randint(0, count - 1)
    for _ in range(random_offset):
        next(cursor)
    
    # Get the random document
    random_document = cursor.next()
    
    client.close()
    return random_document