Random Document Selector from MongoDB Collection

  • Share this:

Code introduction


This function is used to randomly select a document from a MongoDB collection. If a filter is provided, it will filter the documents based on the condition and then randomly select one. If no filter is provided, it will randomly select any document from the collection.


Technology Stack : MongoDB, PyMongo

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def random_document_selector(collection, filter=None):
    from pymongo import MongoClient
    from pymongo.collection import Collection
    from random import choice

    # Establish a connection to the MongoDB server
    client = MongoClient('localhost', 27017)
    db = client['test_database']
    collection = db[collection]

    # Apply the filter if provided
    if filter:
        documents = collection.find(filter)
    else:
        documents = collection.find()

    # Select a random document from the collection
    random_document = choice(list(documents))

    return random_document