Random Document Retrieval from MongoDB Collection

  • Share this:

Code introduction


This function is used to randomly retrieve a document from a specified collection in a MongoDB database. It connects to a local MongoDB instance, specifies the database and collection, and then queries the first document with a string type ID.


Technology Stack : MongoDB, Motor

Code Type : Database operation function

Code Difficulty : Intermediate


                
                    
def find_random_document(db, collection_name):
    from motor.motor_mongodb import MotorClient
    client = MotorClient('localhost', 27017)
    db = client[db]
    collection = db[collection_name]
    random_document = collection.find_one({"_id": {"$type": "string"}})
    client.close()
    return random_document                
              
Tags: