Random Document Access from MongoDB Collection

  • Share this:

Code introduction


This function uses Beanie and Motor libraries to randomly retrieve the value of a document from a specified MongoDB collection.


Technology Stack : Beanie, Motor, MongoDB

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
def random_collection_access(collection_name, key):
    """
    Access a random document from a given Beanie collection by key.
    """
    from beanie import Document
    from motor.motor_asyncio import AsyncIOMotorClient

    # Connect to MongoDB asynchronously
    client = AsyncIOMotorClient('localhost', 27017)
    db = client['mydatabase']

    # Define the schema for the documents
    class CollectionDocument(Document):
        key: str
        value: str

    # Get a random document from the collection
    random_document = CollectionDocument.objects(name=collection_name).limit(1).skip(1).first()
    if random_document:
        return random_document.value
    else:
        return "Collection not found or empty."