Random Document Finder from MongoDB Collection

  • Share this:

Code introduction


This function randomly finds a document from the specified MongoDB collection. It uses `random.sample()` to randomly select an ID from the collection and then uses the `find_one()` method to retrieve the document.


Technology Stack : MongoDB, pymongo, random.sample, find_one

Code Type : The type of code

Code Difficulty : Intermediate


                
                    
def find_random_document(collection):
    import random
    from pymongo import MongoClient

    client = MongoClient('mongodb://localhost:27017/')
    db = client['mydatabase']
    collection = db[collection]

    document = collection.find_one({'_id': {'$in': random.sample(collection.find(), 1)}})
    return document