DEV Community


Posted on

Python Script to Monitor MongoDB

Here is a Python script that checks the status of MongoDB and sends an email using the smtplib library:

import smtplib
from pymongo import MongoClient

Replace these with your own email and MongoDB connection details

sender_email = ""
receiver_email = ""
mongodb_uri = "mongodb://localhost:27017"

Connect to MongoDB

client = MongoClient(mongodb_uri)

Check the status of the server

server_status = client.server_info()

Set the subject and body of the email based on the server status

if "ok" in server_status and server_status["ok"] == 1.0:
subject = "MongoDB status: OK"
body = "The MongoDB server is running and responding to requests."
subject = "MongoDB status: ERROR"
body = "There was a problem connecting to the MongoDB server."

Send the email using SMTP

read full:

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.