You can download this code by clicking the button below.
This code is now available for download.
This function is used to query a random document from a MongoDB collection. It first gets a cursor to the collection using the find method and then converts it to a list. If the document list is not empty, it selects a random document from the list using the random module and returns it.
Technology Stack : MongoDB, pymongo, random
Code Type : The type of code
Code Difficulty : Intermediate
def random_query(collection, filter=None):
"""
Query a MongoDB collection and return a random document based on the filter provided.
"""
# Use the find method to get a cursor to the collection
cursor = collection.find(filter)
# Convert the cursor to a list
documents = list(cursor)
# Check if there are any documents in the collection
if not documents:
return None
# Use the random module to select a random document
import random
import pymongo
random_document = random.choice(documents)
# Return the random document
return random_document
# JSON explanation of the code