You can download this code by clicking the button below.
This code is now available for download.
This function randomly selects and returns a document from a specified collection in a MongoDB database.
Technology Stack : Motor, MongoDB, AsyncIOMotorClient, find, list, random, choice
Code Type : The type of code
Code Difficulty :
def find_random_document(db, collection_name):
# This function finds a random document from a specified collection in a MongoDB database.
from motor.motor_asyncio import AsyncIOMotorClient
import random
client = AsyncIOMotorClient('localhost', 27017)
db = client[db]
collection = db[collection_name]
# Fetch all documents from the collection
documents = list(collection.find())
# Check if the collection is empty
if not documents:
return None
# Select a random document from the collection
random_document = random.choice(documents)
return random_document