Created
August 8, 2025 15:00
-
-
Save samukasmk/d876d2eeec1843669033026187d74d67 to your computer and use it in GitHub Desktop.
Simple script in python to get slow queries in mongodb
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
import datetime | |
from pymongo import MongoClient | |
from bson import json_util | |
# define settings | |
mongodb_uri = "mongodb://<mongodb-user>:<mongodb-password>@<mongodb-host>:<mongodb-port>" | |
secs_running = 3 | |
db_prefix = 'my-db' | |
# get all operations | |
client = MongoClient(mongodb_uri) | |
admin = client.admin | |
operations = admin.command("currentOp", {"allUsers": True}) | |
# print json lines | |
for op in operations.get("inprog", []): | |
# ignoring fields out of custom filters | |
if not op.get("ns") or not op["ns"].startswith(db_prefix): | |
continue | |
if op.get("active") is not True: | |
continue | |
if not op.get("secs_running") or op["secs_running"] < min_secs: | |
continue | |
# format in json | |
log_line = { | |
"timestamp": datetime.datetime.now(datetime.UTC).isoformat() + "Z", | |
"mongo_op": op | |
} | |
print(json_util.dumps(log_line)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment