Random Document Retrieval from MongoDB Collection

  • Share this:

Code introduction


This function randomly finds and returns a document from a MongoDB collection based on the provided query criteria.


Technology Stack : MongoDB, Motor (Python driver for MongoDB)

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def find_random_document(collection, query):
    # This function finds a random document from a MongoDB collection based on a given query.
    cursor = collection.find(query)
    if cursor.count() == 0:
        return None
    random_document = cursor.sample()
    return random_document