Randomly Select and Sort MongoDB Document

  • Share this:

Code introduction


This function randomly selects a document from a MongoDB collection and can apply queries and projections. It also randomly sorts the document fields in descending order.


Technology Stack : MongoDB, pymongo

Code Type : Database Query Function

Code Difficulty : Intermediate


                
                    
def random_select(collection, query=None, projection=None):
    from pymongo import DESCENDING
    import random

    # Ensure the query is a dictionary if it's not None
    if query is not None and not isinstance(query, dict):
        raise ValueError("Query must be a dictionary.")

    # Ensure the projection is a dictionary if it's not None
    if projection is not None and not isinstance(projection, dict):
        raise ValueError("Projection must be a dictionary.")

    # Retrieve a random document from the collection
    random_document = collection.find_one(query, projection)
    
    # If no document is found, return None
    if random_document is None:
        return None

    # Randomly sort the document fields in descending order
    sorted_document = {k: random_document[k] for k in sorted(random_document, reverse=True)}

    return sorted_document