Random Document Selector from MongoDB Collection

  • Share this:

Code introduction


This function randomly selects and returns a document from the specified MongoDB collection.


Technology Stack : MongoDB, pymongo

Code Type : MongoDB query

Code Difficulty : Intermediate


                
                    
def find_random_document(collection):
    from pymongo import MongoClient
    from random import choice

    client = MongoClient('localhost', 27017)
    db = client['testdb']
    collection = db[collection]

    # Find a random document in the collection
    random_document = choice(list(collection.find()))

    return random_document