Random Document Selection from MongoDB Collection

  • Share this:

Code introduction


This function randomly selects and returns a document from the specified MongoDB collection. If a filter condition is provided, it will only select documents that match the condition.


Technology Stack : Python, PyMongo

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def find_random_document(collection, filter={}):
    from pymongo import MongoClient
    from pymongo.collection import Collection
    import random

    client = MongoClient('localhost', 27017)
    db = client['mydatabase']
    col = Collection(db, collection)
    document = random.choice(list(col.find(filter)))
    return document                
              
Tags: