You can download this code by clicking the button below.
This code is now available for download.
This function uses the Beanie library to randomly select documents from a specified collection.
Technology Stack : Beanie
Code Type : Function
Code Difficulty : Intermediate
def random_document_selector(collection, number_of_documents=1):
"""
Selects a random document from a Beanie collection.
Args:
collection (beanie.Collection): The Beanie collection to select from.
number_of_documents (int): The number of documents to select. Default is 1.
Returns:
list: A list of random documents from the collection.
"""
import random
import beanie
# Ensure that the collection is a Beanie collection
if not isinstance(collection, beanie.Collection):
raise ValueError("The collection must be an instance of beanie.Collection")
# Fetch all documents from the collection
documents = list(collection.find())
# Select a random document
selected_documents = random.sample(documents, number_of_documents)
return selected_documents