You can download this code by clicking the button below.
This code is now available for download.
This function uses the Motor library to connect to a MongoDB database, randomly selects a document from the specified collection, and returns it.
Technology Stack : Motor, MongoDB, Python
Code Type : Database operation
Code Difficulty : Intermediate
def get_random_document(collection, query):
import motor.motor_asyncio
from motor.motor_asyncio import AsyncIOMotorClient
import random
# Connect to MongoDB using Motor
client = AsyncIOMotorClient('localhost', 27017)
db = client['mydatabase']
collection = db[collection]
# Query the collection
documents = list(collection.find(query))
# Get a random document
random_document = random.choice(documents)
# Close the connection
client.close()
return random_document