Random Document Insertion into MongoDB Collection

  • Share this:

Code introduction


This function connects to a MongoDB database and attempts to insert a randomly generated document into the specified collection. If the random number is even, the insertion operation is performed.


Technology Stack : pymongo, MongoDB, MongoClient, random

Code Type : Function

Code Difficulty : Intermediate


                
                    
def insert_random_document(db_name, collection_name, document):
    from pymongo import MongoClient
    from random import randint
    
    # Connect to MongoDB
    client = MongoClient('localhost', 27017)
    
    # Select the database
    db = client[db_name]
    
    # Select the collection
    collection = db[collection_name]
    
    # Generate a random integer to decide if we insert the document
    random_number = randint(0, 1)
    
    # Insert the document if the random number is even
    if random_number % 2 == 0:
        collection.insert_one(document)
    
    # Close the connection
    client.close()