Random Document Retrieval from MongoDB Collection

  • Share this:

Code introduction


This function accepts a MongoDB collection and a dictionary of filter conditions as parameters, then performs a random query and returns a random document that matches the filter conditions.


Technology Stack : MongoDB, pymongo

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_query(collection, filter_conditions):
    """
    Perform a random query on a MongoDB collection based on given filter conditions.
    
    :param collection: The MongoDB collection to query.
    :param filter_conditions: A dictionary of filter conditions for the query.
    :return: A random document from the collection that matches the filter conditions.
    """
    # Use the find method to get a cursor for documents matching the filter conditions
    cursor = collection.find(filter_conditions)
    
    # Use the tolist() method to convert the cursor to a list of documents
    documents = list(cursor)
    
    # Check if there are any documents that match the filter conditions
    if not documents:
        return None
    
    # Use the random.choice method to select a random document from the list
    return random.choice(documents)