Random Document Selection from MongoDB using Beanie

  • Share this:

Code introduction


This function uses the Beanie library to connect to a MongoDB database and randomly selects a document from the document collection based on the given query parameter and returns it.


Technology Stack : Beanie, PydanticObjectId, Document, AsyncIOMotorClient, AsyncIOMotorCollection

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_document_selector(document_store, query):
    from beanie import PydanticObjectId
    from beanie import Document
    from motor.motor_asyncio import AsyncIOMotorClient

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

    # Assuming the document store is an instance of AsyncIOMotorCollection
    collection = db['documents']

    # Convert query to an ObjectId if it's a string
    if isinstance(query, str):
        query = PydanticObjectId(query)

    # Query the database for a random document based on the query
    random_document = collection.find_one({"_id": query}, {"_id": 0, "title": 1, "content": 1})

    return random_document