You can download this code by clicking the button below.
This code is now available for download.
This function connects to the MongoDB server, specifies the database name and collection name, and then inserts a document into the collection.
Technology Stack : pymongo
Code Type : Database operation function
Code Difficulty : Intermediate
def random_collection_insert(db_name, collection_name, document):
from pymongo import MongoClient
from pymongo.collection import Collection
# Connect to the MongoDB server
client = MongoClient('localhost', 27017)
# Select the database
db = client[db_name]
# Select the collection
collection = Collection(db, collection_name)
# Insert the document into the collection
collection.insert_one(document)
# Close the connection
client.close()