Random Document Retrieval from MongoDB Collection

  • Share this:

Code introduction


The function retrieves a random document from a specified MongoDB collection based on a filter query. If a projection is provided, only the specified fields are returned.


Technology Stack : pymongo, MongoClient, count_documents, find_one, random, randrange

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_collation(collection, filter_query, projection=None):
    """
    Fetches a random document from a MongoDB collection based on a filter query and an optional projection.

    Args:
        collection (str): The name of the collection from which to fetch the document.
        filter_query (dict): The query to filter documents from the collection.
        projection (dict, optional): The fields to include or exclude from the returned documents.

    Returns:
        dict: A random document from the collection that matches the filter query.
    """
    import pymongo
    from pymongo import MongoClient
    from random import randrange

    # Connect to the MongoDB server
    client = MongoClient('localhost', 27017)
    db = client['test_database']  # Replace 'test_database' with your actual database name
    collection = db[collection]

    # Count the number of documents that match the filter query
    count = collection.count_documents(filter_query)

    # If no documents match the filter query, return None
    if count == 0:
        return None

    # Generate a random index to fetch a random document
    random_index = randrange(count)

    # Fetch the random document
    random_document = collection.find_one(filter_query, projection)

    # Close the connection to the MongoDB server
    client.close()

    return random_document