Random Document Retrieval from MongoDB Collection

  • Share this:

Code introduction


This function retrieves a random document from a specified MongoDB collection based on a provided query criteria. It first calculates the count of documents that match the query, then generates a random index to fetch a document.


Technology Stack : PyMongoEngine, MongoDB, random, DESCENDING, Q

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def random_query_document(collection, query):
    """
    Fetches a random document from a given collection based on a provided query.

    Args:
        collection (mongomongoengine.Document): The MongoDB collection to query.
        query (dict): The query criteria to use for filtering documents.

    Returns:
        dict: A random document that matches the query criteria.
    """
    import random
    from pymongo import DESCENDING
    from mongoengine import Q

    # Calculate the count of documents that match the query
    count = collection.count(Q(**query))

    # Generate a random index to fetch a document
    random_index = random.randint(0, count - 1)

    # Fetch a random document using the random index
    return collection.objects(order_by='__id').skip(random_index).first()