Random Document Retrieval from MongoDB Collection

  • Share this:

Code introduction


This function retrieves a random document from a MongoDB collection. It first creates an index on the _id field for efficient random access, then retrieves a random _id from the collection and uses it to get the corresponding document.


Technology Stack : MongoDB, pymongo

Code Type : Database Query

Code Difficulty : Intermediate


                
                    
def random_document(collection, filter=None):
    """
    This function retrieves a random document from a MongoDB collection.
    
    Args:
    - collection (pymongo.collection.Collection): The MongoDB collection from which to retrieve the document.
    - filter (dict, optional): The filter to apply to the collection. Defaults to None.
    
    Returns:
    - dict: The random document from the collection.
    """
    import random
    from pymongo import DESCENDING
    
    # Create an index on the `_id` field for efficient random access
    collection.create_index([('_id', DESCENDING)])
    
    # Retrieve a random _id from the collection
    random_id = collection.find_one(filter={'_id': {'$exists': True}})['_id']
    
    # Retrieve the document with the random _id
    return collection.find_one({'_id': random_id})