Random Document Retrieval from MongoDB with Motor Library

  • Share this:

Code introduction


This function uses the Motor library to connect to a MongoDB database and randomly query a document that meets a specific query condition from the specified collection.


Technology Stack : Motor, MongoDB, asyncio

Code Type : Function

Code Difficulty : Intermediate


                
                    
def find_random_document(collection, query):
    from motor.motor_asyncio import AsyncIOMotorClient
    import random

    client = AsyncIOMotorClient('localhost', 27017)
    db = client['mydatabase']
    collection = db[collection]

    async def get_random_document():
        documents = await collection.find(query).to_list(None)
        if documents:
            return random.choice(documents)
        return None

    return get_random_document()