Random Document Selection from MongoDB Collection

  • Share this:

Code introduction


This function uses the Motor library to connect to a MongoDB database and randomly selects a specified number of documents from the specified collection.


Technology Stack : Motor, MongoDB, AsyncIOMotorClient, random.sample

Code Type : Function

Code Difficulty : Intermediate


                
                    
def random_motor_collection(collection_id, num_items):
    from motor.motor_asyncio import AsyncIOMotorClient
    import random

    # Connect to the MongoDB instance
    client = AsyncIOMotorClient('localhost', 27017)
    db = client['motor_db']
    collection = db[collection_id]

    # Fetch random documents from the collection
    random_documents = random.sample(collection.find(), num_items)

    # Close the connection
    client.close()

    return random_documents