Random Document Selector from Beanie Database

  • Share this:

Code introduction


This function randomly selects a document from a Beanie database based on a given query. It first retrieves all documents that match the query, and then randomly selects one to return.


Technology Stack : Beanie, Python

Code Type : Database Query and Random Selection

Code Difficulty : Intermediate


                
                    
def random_document_selector(database, query):
    """
    Selects a random document from a Beanie database based on a given query.

    Parameters:
    database (beanie.Database): The Beanie database from which to select a document.
    query (dict): The query to filter documents.

    Returns:
    dict: A random document that matches the query.
    """
    import beanie
    from random import choice

    # Retrieve all documents that match the query
    matching_documents = list(database.find(query))

    # Select a random document from the matching documents
    if matching_documents:
        return choice(matching_documents)
    else:
        return None                
              
Tags: