MongoDB性能监控工具全面解析:从基础到高级实战技巧

引言
MongoDB作为一款流行的NoSQL数据库,其性能监控对于保障系统稳定性和优化查询效率至关重要。本文将全面解析MongoDB性能监控工具,从基础工具到高级实战技巧,帮助您构建完整的监控体系。
一、基础监控工具
1.1 mongostat 和 mongotop
mongostat
是MongoDB自带的实时监控工具,可以显示数据库的实时状态。
# 基本使用
mongostat –host localhost:27017 –username admin –password password –authenticationDatabase admin

# 输出示例(每秒更新)
insert query update delete getmore command dirty used flushes vsize res qr|w ar|w netIn netOut conn time
*0 *0 *0 *0 0 0|0 0.0% 0.0% 0 1.8G 1.1G 0|0 0|0 79b 15k 2 10:30:15
*0 *0 *0 *0 0 0|0 0.0% 0.0% 0 1.8G 1.1G 0|0 0|0 79b 15k 2 10:30:16
mongotop
用于监控每个集合的读写时间。
# 基本使用
mongotop –host localhost:27017 –username admin –password password –authenticationDatabase admin

# 输出示例
ns total read write 2023-10-15T10:30:15+08:00
admin.$cmd 0ms 0ms 0ms
local.oplog.rs 0ms 0ms 0ms
test.users.indexes 0ms 0ms 0ms
test.users 0ms 0ms 0ms
1.2 db.serverStatus()
通过MongoDB Shell获取详细的服务器状态信息。
// 连接到MongoDB
mongo –host localhost:27017 –username admin –password password –authenticationDatabase admin

// 获取服务器状态
db.serverStatus()

// 重点关注的字段
{
“uptime”: 86400, // 运行时间(秒)
“connections”: {
“current”: 42, // 当前连接数
“available”: 8190, // 可用连接数
“totalCreated”: 1000 // 总创建连接数
},
“globalLock”: {
“totalTime”: 86400000000, // 总时间(微秒)
“lockTime”: 1000000, // 锁定时间(微秒)
“currentQueue”: {
“total”: 0, // 当前队列总数
“readers”: 0, // 读队列
“writers”: 0 // 写队列
}
},
“mem”: {
“resident”: 1100, // 物理内存使用(MB)
“virtual”: 1800, // 虚拟内存使用(MB)
“mapped”: 1600 // 映射内存(MB)
},
“opcounters”: {
“insert”: 1000, // 插入操作数
“query”: 5000, // 查询操作数
“update”: 200, // 更新操作数
“delete”: 50, // 删除操作数
“command”: 3000 // 命令操作数
},
“opcountersRepl”: {
“insert”: 0,
“query”: 0,
“update”: 0,
“delete”: 0,
“command”: 0
},
“network”: {
“bytesIn”: 1000000, // 接收字节数
“bytesOut”: 2000000, // 发送字节数
“numRequests”: 10000 // 请求数
}
}
1.3 db.currentOp()
查看当前正在执行的操作。
// 查看所有正在执行的操作
db.currentOp()

// 查看特定数据库的操作
db.currentOp({
“ns”: /^test\./,
“active”: true
})

// 查看执行时间超过1秒的操作
db.currentOp({
“active”: true,
“secs_running”: { “$gt”: 1 }
})

// 输出示例
{
“inprog”: [
{
“opid”: 12345,
“active”: true,
“secs_running”: 5,
“op”: “query”,
“ns”: “test.users”,
“query”: { “age”: { “$gt”: 25 } },
“planSummary”: “IXSCAN { age: 1 }”,
“client”: “127.0.0.1:54321”,
“appName”: “MyApp”
}
]
}
1.4 db.killOp()
终止正在执行的操作。
// 终止特定操作
db.killOp(12345)

// 终止所有长时间运行的操作
db.currentOp({
“active”: true,
“secs_running”: { “$gt”: 10 }
}).inprog.forEach(function(op) {
db.killOp(op.opid);
print(“Killed operation: ” + op.opid);
});
二、高级监控工具
2.1 MongoDB Atlas Performance Advisor
MongoDB Atlas的性能顾问功能可以自动分析查询性能并提供优化建议。
使用示例:
登录MongoDB Atlas控制台
进入”Performance”选项卡
查看”Performance Advisor”建议
优化建议示例:
// 原始查询(低效)
db.users.find({
“age”: { “$gte”: 18, “$lte”: 30 },
“city”: “New York”,
“status”: “active”
}).sort({ “createdAt”: -1 }).limit(100)

// 优化建议:创建复合索引
db.users.createIndex({
“city”: 1,
“status”: 1,
“age”: 1,
“createdAt”: -1
})

// 优化后的查询(高效)
db.users.find({
“age”: { “$gte”: 18, “$lte”: 30 },
“city”: “New York”,
“status”: “active”
}).sort({ “createdAt”: -1 }).limit(100)
2.2 MongoDB Ops Manager
MongoDB Ops Manager是企业级监控和管理平台。
安装和配置:
# 下载Ops Manager
wget https://downloads.mongodb.com/ops-manager/ops-manager-5.0.0.tar.gz

# 解压
tar -xzf ops-manager-5.0.0.tar.gz

# 配置
cd ops-manager-5.0.0
./bin/mms-ctl config

# 启动
./bin/mms-ctl start
监控配置示例:
# ops-manager-config.yaml
mms:
central:
host: “localhost”
port: 8080
agent:
host: “localhost”
port: 27017
user: “admin”
password: “password”
authSource: “admin”
2.3 Prometheus + Grafana
开源监控方案,适合自建监控系统。
安装Prometheus:
# 下载Prometheus
wget https://github.com/prometheus/prometheus/releases/download/v2.45.0/prometheus-2.45.0.linux-amd64.tar.gz

# 解压
tar xvfz prometheus-2.45.0.linux-amd64.tar.gz

# 配置
cat > prometheus.yml << EOF global: scrape_interval: 15s scrape_configs: - job_name: 'mongodb' static_configs: - targets: ['localhost:9211'] EOF # 启动 ./prometheus --config.file=prometheus.yml 安装MongoDB Exporter: # 下载MongoDB Exporter wget https://github.com/percona/mongodb_exporter/releases/download/v0.40.0/mongodb_exporter-0.40.0.linux-amd64.tar.gz # 解压 tar xvfz mongodb_exporter-0.40.0.linux-amd64.tar.gz # 启动 ./mongodb_exporter --mongodb.uri="mongodb://admin:password@localhost:27017/admin" --web.listen-address=":9211" Grafana配置: 安装Grafana 添加Prometheus数据源 导入MongoDB监控仪表板(ID:2583) 2.4 MongoDB Compass MongoDB官方GUI工具,提供可视化监控。 安装: # Ubuntu/Debian wget https://downloads.mongodb.com/compass/mongodb-compass_1.38.0_amd64.deb sudo dpkg -i mongodb-compass_1.38.0_amd64.deb # macOS brew install --cask mongodb-compass 性能监控功能: 连接到MongoDB实例 点击”Performance”选项卡 查看实时性能图表 分析慢查询 三、实战技巧 3.1 慢查询分析 启用慢查询日志: // 在MongoDB配置文件中添加 systemLog: destination: file path: "/var/log/mongodb/mongod.log" logAppend: true operationProfiling: mode: slowOp slowOpThresholdMs: 100 slowOpSampleRate: 1.0 分析慢查询日志: # 查找慢查询 grep "command" /var/log/mongodb/mongod.log | grep "ms" # 使用mongodump分析 mongodump --host localhost:27017 --db admin --collection system.profile --out /tmp/profile 使用explain()分析查询: // 基本explain db.users.find({ age: { $gte: 25 } }).explain("executionStats") // 详细explain db.users.find({ age: { $gte: 25 }, city: "New York" }).explain({ "verbosity": "executionStats", "explainFilters": { "allPlansExecution": true } }) 3.2 索引优化 索引使用情况监控: // 查看索引使用统计 db.users.aggregate([ { $indexStats: { } } ]) // 查看未使用的索引 db.users.aggregate([ { $indexStats: { } }, { $match: { "accesses.ops": 0 } } ]) 索引创建策略: // 1. 复合索引(最左前缀原则) db.users.createIndex({ "city": 1, "status": 1, "age": 1 }) // 2. 覆盖索引 db.users.createIndex({ "age": 1, "name": 1, "email": 1 }) // 3. 地理空间索引 db.places.createIndex({ "location": "2dsphere" }) // 4. 文本索引 db.articles.createIndex({ "content": "text" }) // 5. TTL索引(自动过期) db.sessions.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } ) 3.3 连接池管理 监控连接池: // 查看连接池状态 db.serverStatus().connections // 查看连接详情 db.serverStatus().network // 监控连接数变化 function monitorConnections() { var stats = db.serverStatus(); print("当前连接数: " + stats.connections.current); print("可用连接数: " + stats.connections.available); print("总创建连接数: " + stats.connections.totalCreated); } // 定时监控 setInterval(monitorConnections, 5000); 优化连接配置: // 在应用代码中配置连接池 const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/mydb', { useNewUrlParser: true, useUnifiedTopology: true, maxPoolSize: 100, // 最大连接数 minPoolSize: 10, // 最小连接数 maxIdleTimeMS: 30000, // 最大空闲时间 socketTimeoutMS: 45000, // 套接字超时 serverSelectionTimeoutMS: 5000 // 服务器选择超时 }); 3.4 内存使用优化 监控内存使用: // 查看内存使用情况 db.serverStatus().mem // 查看内存映射文件 db.serverStatus().mem.mapped // 查看缓存命中率 db.serverStatus().wiredTiger.cache // 计算缓存命中率 function calculateCacheHitRate() { var cache = db.serverStatus().wiredTiger.cache; var read = cache["pages read into cache"]; var write = cache["pages written from cache"]; var hitRate = (read - write) / read * 100; print("缓存命中率: " + hitRate.toFixed(2) + "%"); } 优化内存配置: // 在MongoDB配置文件中设置 storage: wiredTiger: engineConfig: cacheSizeGB: 8 # 根据系统内存调整,通常为系统内存的50% journalCompressor: snappy collectionConfig: blockCompressor: snappy indexConfig: prefixCompression: true # 或者在运行时调整 db.adminCommand({ setParameter: 1, wiredTigerEngineRuntimeConfig: "cache_size=8GB" }); 3.5 复制集监控 监控复制集状态: // 查看复制集状态 rs.status() // 查看复制延迟 rs.printSlaveReplicationInfo() // 查看oplog状态 db.getReplicationInfo() // 监控复制队列 function monitorReplicationQueue() { var status = rs.status(); status.members.forEach(function(member) { if (member.stateStr === "SECONDARY") { print("节点: " + member.name); print("状态: " + member.stateStr); print("延迟: " + member.optimeDate + "秒"); } }); } 配置监控脚本: // replication_monitor.js const { MongoClient } = require('mongodb'); async function monitorReplication() { const client = new MongoClient('mongodb://localhost:27017'); try { await client.connect(); const adminDb = client.db('admin'); // 获取复制集状态 const status = await adminDb.command({ replSetGetStatus: 1 }); // 分析每个成员 status.members.forEach(member => {
console.log(`节点: ${member.name}`);
console.log(`状态: ${member.stateStr}`);
console.log(`延迟: ${member.optimeDate}`);
console.log(‘—‘);
});

// 检查延迟
const maxDelay = Math.max(…status.members.map(m =>
m.optimeDate ? (Date.now() – m.optimeDate.getTime()) / 1000 : 0
));

if (maxDelay > 30) {
console.warn(`复制延迟过高: ${maxDelay}秒`);
}

} finally {
await client.close();
}
}

// 定时执行
setInterval(monitorReplication, 60000);
3.6 分片集群监控
监控分片集群:
// 查看分片状态
sh.status()

// 查看分片键分布
db.users.getShardDistribution()

// 监控分片均衡
function monitorSharding() {
var config = db.getSiblingDB(“config”);

// 检查均衡器状态
var balancer = config.settings.findOne({ _id: “balancer” });
print(“均衡器状态: ” + (balancer ? balancer.enabled : “unknown”));

// 检查块分布
var chunks = config.chunks.find({ ns: “test.users” }).toArray();
print(“总块数: ” + chunks.length);

// 检查分片负载
var shards = config.shards.find().toArray();
shards.forEach(function(shard) {
var count = config.chunks.count({ shard: shard._id });
print(“分片 ” + shard._id + ” 块数: ” + count);
});
}
分片键优化:
// 1. 选择合适的分片键
// 好的分片键:cardinality高、分布均匀、查询模式匹配
db.users.createIndex({ “userId”: 1, “createdAt”: 1 })

// 2. 启用分片
sh.enableSharding(“test”)
sh.shardCollection(“test.users”, { “userId”: 1, “createdAt”: 1 })

// 3. 监控分片键分布
function analyzeShardDistribution() {
var stats = db.users.aggregate([
{ $group: { _id: “$userId”, count: { $sum: 1 } } },
{ $group: { _id: null, total: { $sum: 1 }, avg: { $avg: “$count” } } }
]).toArray();

print(“总用户数: ” + stats[0].total);
print(“平均每个用户文档数: ” + stats[0].avg);
}
四、自动化监控脚本
4.1 健康检查脚本
// health_check.js
const { MongoClient } = require(‘mongodb’);
const fs = require(‘fs’);

class MongoDBHealthCheck {
constructor(config) {
this.config = config;
this.client = null;
}

async connect() {
this.client = new MongoClient(this.config.uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000
});

await this.client.connect();
return this.client;
}

async checkConnection() {
try {
const start = Date.now();
await this.client.db(‘admin’).command({ ping: 1 });
const latency = Date.now() – start;
return { status: ‘healthy’, latency };
} catch (error) {
return { status: ‘unhealthy’, error: error.message };
}
}

async checkReplication() {
try {
const status = await this.client.db(‘admin’).command({ replSetGetStatus: 1 });
const members = status.members;

// 检查主节点
const primary = members.find(m => m.stateStr === ‘PRIMARY’);
if (!primary) {
return { status: ‘unhealthy’, error: ‘No primary node’ };
}

// 检查复制延迟
const maxDelay = Math.max(…members.map(m =>
m.optimeDate ? (Date.now() – m.optimeDate.getTime()) / 1000 : 0
));

return {
status: maxDelay > 30 ? ‘warning’ : ‘healthy’,
primary: primary.name,
maxDelay
};
} catch (error) {
return { status: ‘unhealthy’, error: error.message };
}
}

async checkMemory() {
try {
const status = await this.client.db(‘admin’).command({ serverStatus: 1 });
const mem = status.mem;

const usage = {
resident: mem.resident,
virtual: mem.virtual,
mapped: mem.mapped,
usagePercent: (mem.resident / mem.virtual * 100).toFixed(2)
};

return {
status: usage.usagePercent > 80 ? ‘warning’ : ‘healthy’,
memory: usage
};
} catch (error) {
return { status: ‘unhealthy’, error: error.message };
}
}

async checkConnections() {
try {
const status = await this.client.db(‘admin’).command({ serverStatus: 1 });
const connections = status.connections;

const usage = {
current: connections.current,
available: connections.available,
total: connections.current + connections.available,
usagePercent: (connections.current / (connections.current + connections.available) * 100).toFixed(2)
};

return {
status: usage.usagePercent > 80 ? ‘warning’ : ‘healthy’,
connections: usage
};
} catch (error) {
return { status: ‘unhealthy’, error: error.message };
}
}

async checkDisk() {
try {
const status = await this.client.db(‘admin’).command({ serverStatus: 1 });
const storage = status.storageEngine;

// 检查磁盘空间(需要系统命令)
const { execSync } = require(‘child_process’);
const df = execSync(‘df -h /var/lib/mongodb’).toString();

return {
status: ‘healthy’,
disk: df
};
} catch (error) {
return { status: ‘unhealthy’, error: error.message };
}
}

async runAllChecks() {
const results = {
timestamp: new Date().toISOString(),
checks: {}
};

// 并行执行所有检查
const checks = [
{ name: ‘connection’, check: this.checkConnection() },
{ name: ‘replication’, check: this.checkReplication() },
{ name: ‘memory’, check: this.checkMemory() },
{ name: ‘connections’, check: this.checkConnections() },
{ name: ‘disk’, check: this.checkDisk() }
];

for (const { name, check } of checks) {
results.checks[name] = await check;
}

// 计算整体状态
const unhealthy = Object.values(results.checks).filter(c => c.status === ‘unhealthy’).length;
const warning = Object.values(results.checks).filter(c => c.status === ‘warning’).length;

if (unhealthy > 0) {
results.overallStatus = ‘unhealthy’;
} else if (warning > 0) {
results.overallStatus = ‘warning’;
} else {
results.overallStatus = ‘healthy’;
}

return results;
}

async close() {
if (this.client) {
await this.client.close();
}
}
}

// 使用示例
async function main() {
const config = {
uri: ‘mongodb://admin:password@localhost:27017/admin’
};

const healthCheck = new MongoDBHealthCheck(config);

try {
await healthCheck.connect();
const results = await healthCheck.runAllChecks();

console.log(JSON.stringify(results, null, 2));

// 保存结果到文件
fs.writeFileSync(
`/tmp/mongodb_health_${Date.now()}.json`,
JSON.stringify(results, null, 2)
);

// 发送告警(如果需要)
if (results.overallStatus === ‘unhealthy’) {
// 这里可以集成邮件、Slack等告警系统
console.error(‘MongoDB健康检查失败!’);
}

} catch (error) {
console.error(‘健康检查执行失败:’, error);
} finally {
await healthCheck.close();
}
}

// 定时执行
if (require.main === module) {
// 立即执行一次
main();

// 每5分钟执行一次
setInterval(main, 5 * 60 * 1000);
}
4.2 性能数据收集脚本
// performance_collector.js
const { MongoClient } = require(‘mongodb’);
const fs = require(‘fs’);
const path = require(‘path’);

class PerformanceCollector {
constructor(config) {
this.config = config;
this.client = null;
this.dataDir = config.dataDir || ‘/var/log/mongodb/performance’;

// 确保数据目录存在
if (!fs.existsSync(this.dataDir)) {
fs.mkdirSync(this.dataDir, { recursive: true });
}
}

async connect() {
this.client = new MongoClient(this.config.uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});

await this.client.connect();
return this.client;
}

async collectServerStatus() {
const status = await this.client.db(‘admin’).command({ serverStatus: 1 });

const metrics = {
timestamp: new Date().toISOString(),
uptime: status.uptime,
connections: status.connections,
mem: status.mem,
opcounters: status.opcounters,
network: status.network,
wiredTiger: status.wiredTiger,
globalLock: status.globalLock
};

return metrics;
}

async collectDatabaseStats() {
const databases = await this.client.db().admin().listDatabases();
const stats = [];

for (const db of databases.databases) {
const dbStats = await this.client.db(db.name).stats();
stats.push({
database: db.name,
collections: dbStats.collections,
objects: dbStats.objects,
dataSize: dbStats.dataSize,
storageSize: dbStats.storageSize,
indexSize: dbStats.indexSize,
scaleFactor: dbStats.scaleFactor
});
}

return stats;
}

async collectCollectionStats() {
const collections = await this.client.db().listCollections().toArray();
const stats = [];

for (const coll of collections) {
const collStats = await this.client.db().collection(coll.name).stats();
stats.push({
collection: coll.name,
count: collStats.count,
size: collStats.size,
storageSize: collStats.storageSize,
totalIndexSize: collStats.totalIndexSize,
avgObjSize: collStats.avgObjSize,
nindexes: collStats.nindexes
});
}

return stats;
}

async collectIndexStats() {
const collections = await this.client.db().listCollections().toArray();
const indexStats = [];

for (const coll of collections) {
const indexes = await this.client.db().collection(coll.name).indexes();

for (const index of indexes) {
const stats = await this.client.db().collection(coll.name).aggregate([
{ $indexStats: { } },
{ $match: { “name”: index.name } }
]).toArray();

if (stats.length > 0) {
indexStats.push({
collection: coll.name,
index: index.name,
key: index.key,
accesses: stats[0].accesses ? stats[0].accesses.ops : 0
});
}
}
}

return indexStats;
}

async collectSlowQueries() {
const slowQueries = await this.client.db().collection(‘system.profile’).find({
“millis”: { “$gt”: 100 }
}).sort({ “ts”: -1 }).limit(100).toArray();

return slowQueries.map(q => ({
timestamp: q.ts,
operation: q.op,
namespace: q.ns,
millis: q.millis,
query: q.command,
planSummary: q.planSummary
}));
}

async collectAllMetrics() {
const metrics = {
timestamp: new Date().toISOString(),
serverStatus: await this.collectServerStatus(),
databaseStats: await this.collectDatabaseStats(),
collectionStats: await this.collectCollectionStats(),
indexStats: await this.collectIndexStats(),
slowQueries: await this.collectSlowQueries()
};

return metrics;
}

async saveMetrics(metrics) {
const timestamp = new Date().toISOString().replace(/[:.]/g, ‘-‘);
const filename = path.join(this.dataDir, `metrics_${timestamp}.json`);

fs.writeFileSync(filename, JSON.stringify(metrics, null, 2));

// 保留最近100个文件
const files = fs.readdirSync(this.dataDir)
.filter(f => f.startsWith(‘metrics_’))
.sort()
.reverse();

if (files.length > 100) {
files.slice(100).forEach(f => {
fs.unlinkSync(path.join(this.dataDir, f));
});
}

return filename;
}

async run() {
try {
const metrics = await this.collectAllMetrics();
const filename = await this.saveMetrics(metrics);

console.log(`Metrics collected and saved to: ${filename}`);

// 分析并生成报告
this.generateReport(metrics);

return metrics;
} catch (error) {
console.error(‘Failed to collect metrics:’, error);
throw error;
}
}

generateReport(metrics) {
const report = {
timestamp: metrics.timestamp,
summary: {
totalDatabases: metrics.databaseStats.length,
totalCollections: metrics.collectionStats.length,
totalIndexes: metrics.indexStats.length,
slowQueries: metrics.slowQueries.length
},
issues: []
};

// 检查连接数
const connections = metrics.serverStatus.connections;
if (connections.current > connections.available * 0.8) {
report.issues.push({
type: ‘connection’,
severity: ‘warning’,
message: `High connection usage: ${connections.current}/${connections.available}`
});
}

// 检查内存使用
const mem = metrics.serverStatus.mem;
if (mem.resident > mem.virtual * 0.8) {
report.issues.push({
type: ‘memory’,
severity: ‘warning’,
message: `High memory usage: ${mem.resident}MB/${mem.virtual}MB`
});
}

// 检查慢查询
if (metrics.slowQueries.length > 10) {
report.issues.push({
type: ‘slowQuery’,
severity: ‘warning’,
message: `High number of slow queries: ${metrics.slowQueries.length}`
});
}

// 检查未使用的索引
const unusedIndexes = metrics.indexStats.filter(i => i.accesses === 0);
if (unusedIndexes.length > 0) {
report.issues.push({
type: ‘index’,
severity: ‘info’,
message: `Found ${unusedIndexes.length} unused indexes`
});
}

// 保存报告
const reportFile = path.join(this.dataDir, `report_${new Date().toISOString().replace(/[:.]/g, ‘-‘)}.json`);
fs.writeFileSync(reportFile, JSON.stringify(report, null, 2));

console.log(‘Performance report generated:’, reportFile);

return report;
}

async close() {
if (this.client) {
await this.client.close();
}
}
}

// 使用示例
async function main() {
const config = {
uri: ‘mongodb://admin:password@localhost:27017/admin’,
dataDir: ‘/var/log/mongodb/performance’
};

const collector = new PerformanceCollector(config);

try {
await collector.connect();
await collector.run();
} catch (error) {
console.error(‘Performance collection failed:’, error);
} finally {
await collector.close();
}
}

// 定时执行
if (require.main === module) {
// 立即执行一次
main();

// 每10分钟执行一次
setInterval(main, 10 * 60 * 1000);
}
五、最佳实践
5.1 监控策略
分层监控
:
基础层:系统资源(CPU、内存、磁盘)
数据库层:连接数、操作数、锁等待
应用层:查询性能、索引使用、复制延迟
告警阈值设置
:
// 告警阈值配置示例
const alertThresholds = {
connection: {
warning: 0.8, // 80%连接使用率
critical: 0.9 // 90%连接使用率
},
memory: {
warning: 0.7, // 70%内存使用率
critical: 0.85 // 85%内存使用率
},
replication: {
warning: 30, // 30秒延迟
critical: 60 // 60秒延迟
},
slowQuery: {
warning: 10, // 10个慢查询/分钟
critical: 50 // 50个慢查询/分钟
}
};
监控频率
:
实时监控:每秒(mongostat)
短期监控:每分钟(脚本收集)
长期监控:每小时/每天(聚合分析)
5.2 性能优化流程
识别瓶颈
:
// 使用db.currentOp()识别慢操作
db.currentOp({
“active”: true,
“secs_running”: { “$gt”: 5 }
})
分析查询计划
:
// 使用explain()分析
db.collection.find(query).explain(“executionStats”)
优化索引
:
// 创建合适的索引
db.collection.createIndex({ field1: 1, field2: -1 })
验证优化效果
:
“`javascript
// 比较优化前后的性能
// 优化前
var start = Date.now();
db.collection.find(query).toArray();
var time1 = Date.now() – start;
// 优化后
start = Date.now();
db.collection.find(query).toArray();
var time2 = Date.now() – start;
print(“优化前: ” + time1 + “ms”);
print(“优化后: ” + time2 + “ms”);
print(“提升: ” + ((time1 – time2) / time1 * 100).toFixed(2) + “%”);
### 5.3 安全考虑

1. **监控权限**:
“`javascript
// 创建只读监控用户
db.createUser({
user: “monitor”,
pwd: “secure_password”,
roles: [
{ role: “clusterMonitor”, db: “admin” },
{ role: “readAnyDatabase”, db: “admin” }
]
})
数据加密
:
“`javascript
// 启用传输加密
mongod –sslMode requireSSL –sslPEMKeyFile /path/to/mongodb.pem
// 启用静态加密
mongod –enableEncryption –encryptionKeyFile /path/to/keyfile
3. **审计日志**:
“`javascript
// 启用审计日志
mongod –auditDestination file –auditFilter ‘{ atype: { $in: [“authCheck”, “write”, “read”] } }’
六、总结
MongoDB性能监控是一个持续的过程,需要结合多种工具和方法。通过本文介绍的工具和技巧,您可以:
实时监控
:使用mongostat、mongotop等工具实时了解数据库状态
深度分析
:使用explain()、db.currentOp()等工具深入分析性能问题
自动化监控
:编写脚本实现自动化监控和告警
可视化展示
:使用Grafana等工具创建监控仪表板
持续优化
:根据监控数据持续优化数据库性能
记住,监控不是目的,而是手段。最终目标是通过监控发现问题、优化性能、保障业务稳定运行。建议根据实际业务需求,选择合适的监控工具组合,建立完善的监控体系。