Random Document Selector for MongoDB Collections

  • Share this:

Code introduction


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


Technology Stack : pymongo, MongoDB

Code Type : Database Query

Code Difficulty : Intermediate


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

    # Connect to the MongoDB client
    client = MongoClient('mongodb://localhost:27017/')

    # Select a database
    db = client['testdb']

    # Select a collection
    collection = db[collection_name]

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

    return random_document