Random Document Finder

  • Share this:

Code introduction


This function accepts a collection name and a query condition, then randomly returns a document that matches the query condition from the collection. If no documents match the condition, it returns None.


Technology Stack : PyMongoEngine, pymongo, random

Code Type : Database query

Code Difficulty : Intermediate


                
                    
def find_random_document(collection_name, query):
    from pymongo import MongoClient
    from random import choice
    
    client = MongoClient('localhost', 27017)
    db = client['mydatabase']
    collection = db[collection_name]
    
    documents = list(collection.find(query))
    if documents:
        return choice(documents)
    else:
        return None