8 Essential MongoDB Admin Scripts to Master Database Management
This guide presents eight practical MongoDB shell scripts—covering database size analysis, connection monitoring, long‑running query termination, table‑scan detection, replica‑set health checks, and slow‑query profiling—plus usage tips and cautions for reliable administration.
Prerequisite – mongosh
All scripts must be executed with mongosh. If it is not installed, download the MongoDB Shell binary from https://www.mongodb.com/try/download/shell and place it in /bin on Linux.
Script 1 – Database Size Overview
Analyzes every database and its collections, reporting total document count, average object size, collection size, and overall storage consumption.
db = connect('mongodb://root:[email protected]:27027/admin');
var databases = db.adminCommand({ listDatabases: 1 }).databases;
databases.forEach(function(dbInfo) {
print("Database Name: " + dbInfo.name);
});
dbStats = db.runCommand({ dbStats: 1 });
collectionStats = db.getCollectionNames().map(function(collectionName) {
return db.getCollection(collectionName).stats();
});
print("=== Database Statistics ===");
print("Database Name: " + dbStats.db);
print("Number of Collections: " + collectionStats.length);
totalDocuments = 0;
totalAvgObjSize = 0;
totalDataSize = 0;
collectionStats.forEach(function(collection) {
totalDocuments += collection.count;
totalAvgObjSize += collection.avgObjSize || 0;
totalDataSize += collection.size;
print("Collection: " + collection.ns);
print(" Document Count: " + collection.count);
print(" Avg Object Size: " + (collection.avgObjSize / 1024).toFixed(2) + " KB");
print(" Collection Size: " + (collection.size / 1024 / 1024).toFixed(2) + " MB");
});
print("=== Summary ===");
print("Total Documents: " + totalDocuments);
print("Total Avg Object Size: " + (totalAvgObjSize / collectionStats.length / 1024).toFixed(2) + " KB");
print("Total Data Size: " + (totalDataSize / 1024 / 1024).toFixed(2) + " MB");Script 2 – Connection Activity Summary
Lists each client connection with application name, operation ID, database, running time, and categorises the connection as active, idle or error.
db = connect('mongodb://root:[email protected]:27027/test');
var operations = db.currentOp();
var activeConnections = 0;
var idleConnections = 0;
var errorConnections = 0;
operations.inprog.forEach(function(op) {
if (op.hasOwnProperty('client')) {
print("Client Address: " + op.client);
print("App Name: " + (op.appName ? op.appName : "N/A"));
print("Operation ID (opid): " + op.opid);
print("Database: " + (op.ns ? op.ns.split('.')[0] : "N/A"));
print("Secs Running: " + (op.hasOwnProperty('secs_running') ? op.secs_running : "N/A") + " seconds");
if (op.active) {
activeConnections++;
print(" Status: Active");
} else if (!op.active && op.hasOwnProperty('secs_running') && op.secs_running == 0) {
idleConnections++;
print(" Status: Idle");
} else if (op.hasOwnProperty('msg') && op.msg == "error") {
errorConnections++;
print(" Status: Error");
}
print("");
}
});
print("
=== Connection Summary ===");
print("Active Connections: " + activeConnections);
print("Idle Connections: " + idleConnections);
print("Error Connections: " + errorConnections);Script 3 – Detailed Connection Statistics
Similar to Script 2 but prints a summary after iterating, useful for a quick overview of active, idle, and error connections.
db = connect('mongodb://root:[email protected]:27027/test');
var operations = db.currentOp();
var activeConnections = 0;
var idleConnections = 0;
var errorConnections = 0;
operations.inprog.forEach(function(op) {
if (op.hasOwnProperty('client')) {
print("Client Address: " + op.client);
print("App Name: " + (op.appName ? op.appName : "N/A"));
print("Operation ID (opid): " + op.opid);
print("Database: " + (op.ns ? op.ns.split('.')[0] : "N/A"));
print("Secs Running: " + (op.hasOwnProperty('secs_running') ? op.secs_running : "N/A") + " seconds");
if (op.active) {
activeConnections++;
print(" Status: Active");
} else if (!op.active && op.hasOwnProperty('secs_running') && op.secs_running == 0) {
idleConnections++;
print(" Status: Idle");
} else if (op.hasOwnProperty('msg') && op.msg == "error") {
errorConnections++;
print(" Status: Error");
}
print("");
}
});
print("
=== Connection Summary ===");
print("Active Connections: " + activeConnections);
print("Idle Connections: " + idleConnections);
print("Error Connections: " + errorConnections);Script 4 – Kill Long‑Running Queries
Terminates any query that has been running longer than a configurable threshold (default 30 seconds). The script prints query details and prompts for confirmation before killing.
db = connect('mongodb://root:[email protected]:27027/test');
var operations = db.currentOp();
operations.inprog.forEach(function(op) {
if (op.secs_running > 30 && op.op === 'query' && !op.killPending) {
print("
=== Query Details ===");
print("Operation ID (opid): " + op.opid);
print("Running for: " + op.secs_running + " seconds");
print("Client: " + op.client);
print("Database: " + (op.ns ? op.ns.split('.')[0] : "N/A"));
print("Collection: " + (op.ns ? op.ns.split('.')[1] : "N/A"));
print("Query: " + tojson(op.query));
var killOp = prompt("Kill this query? (Y/N): ");
if (killOp.toLowerCase() === 'y') {
print("Killing opid: " + op.opid);
db.killOp(op.opid);
} else {
print("Skipping opid: " + op.opid);
}
}
});Script 5 – Detect Potential Table Scans
Inspects current operations to identify queries that are likely to cause a full collection scan (e.g., missing an indexed _id filter) and prints their details.
db = connect('mongodb://root:[email protected]:27027/test');
var operations = db.currentOp();
function isTableScan(query) {
if (!query || Object.keys(query).length === 0) return true;
if (!query.hasOwnProperty('_id')) return true;
return false;
}
var hasTableScan = false;
operations.inprog.forEach(function(op) {
if (op.op === 'query' && !op.killPending) {
var query = op.query;
if (isTableScan(query)) {
hasTableScan = true;
print("
=== Potential Table Scan Detected ===");
print("Operation ID (opid): " + op.opid);
print("Client: " + op.client);
print("Database: " + (op.ns ? op.ns.split('.')[0] : "N/A"));
print("Collection: " + (op.ns ? op.ns.split('.')[1] : "N/A"));
print("Query: " + tojson(query));
}
}
});
if (!hasTableScan) {
print("No full collection scans detected.");
}Script 7 – Replica Set Health and Relationships
Shows replica‑set topology, role of each member (primary, secondary, arbiter, hidden), health status, sync source, and last election time.
db = connect('mongodb://root:[email protected]:27027/test');
var serverStatus = db.serverStatus();
print("MongoDB uptime (seconds): " + serverStatus.uptime);
var isMaster = db.isMaster();
if (isMaster.ismaster) {
print("MongoDB mode: Primary");
} else if (isMaster.secondary) {
print("MongoDB mode: Secondary");
} else {
print("MongoDB mode: Standalone or other");
}
if (isMaster.setName) {
print("Replica set name: " + isMaster.setName);
var replStatus = rs.status();
replStatus.members.forEach(function(member) {
print("
Member: " + member.name);
print(" State: " + member.stateStr);
if (member.stateStr === "PRIMARY") {
print(" Role: Primary");
} else if (member.stateStr === "SECONDARY") {
print(" Role: Secondary");
} else if (member.stateStr === "ARBITER") {
print(" Role: Arbiter");
} else if (member.hidden) {
print(" Role: Hidden");
}
print(" Health: " + (member.health === 1 ? "OK" : "FAIL"));
if (member.syncingTo) {
print(" Syncing to: " + member.syncingTo);
}
if (member.electionDate) {
print(" Last election: " + member.electionDate);
}
});
} else {
print("MongoDB is not part of a replica set.");
}Script 8 – Collect Slow Query Logs
Enables profiling with a 100 ms threshold, waits ten minutes, then prints all captured slow queries with timestamps, execution time, query shape, database, and operation type.
db = connect('mongodb://root:[email protected]:27027/test');
print("Setting slow‑query threshold to 100 ms...");
db.setProfilingLevel(1, 100);
function collectSlowQueries() {
print("
=== Collected Slow Query Logs ===");
var slowQueries = db.system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 });
slowQueries.forEach(function(query) {
print("Query Time: " + query.ts);
print("Execution Time (ms): " + query.millis);
if (query.query) {
print("Query Operation:");
printjson(query.query);
} else {
print("Query Operation: No query filter (e.g., insert)");
}
print("Database: " + query.ns);
if (query.op) {
print("Full Operation: " + query.op);
} else {
print("Full Operation: N/A");
}
print("
");
});
}
print("Starting slow‑query collection, waiting 10 minutes...");
var startTime = new Date().getTime();
var elapsed = 0;
var waitTime = 10 * 60 * 1000;
while (elapsed < waitTime) {
var currentTime = new Date().getTime();
elapsed = currentTime - startTime;
}
print("Collecting 10‑minute slow‑query data...");
collectSlowQueries();
db.setProfilingLevel(0);
print("Slow‑query profiling disabled.");Important Note
Several scripts default to the test database. If your environment does not contain this database, the scripts will fail. Replace the connection string with the correct username, password, host, port, and target database before execution.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
