Random Document Selector for MongoDB Collection

  • Share this:

Code introduction


This function randomly selects a document from the specified MongoDB collection and returns it. It first connects to the MongoDB database, then retrieves all documents, and randomly selects one to return. If there are no documents, it returns None.


Technology Stack : Motor, MongoDB, asyncio

Code Type : Asynchronous MongoDB database operations

Code Difficulty : Intermediate


                
                    
def find_random_document(db, collection_name):
    from motor.motor_asyncio import AsyncIOMotorClient
    from motor.motor_asyncio import AsyncIOMotorCollection
    import random

    client = AsyncIOMotorClient('localhost', 27017)
    collection = client[collection_name]
    documents = await collection.find({}).to_list(None)
    random_document = random.choice(documents) if documents else None
    client.close()
    return random_document