MongoDB在Ubuntu上的性能调优技巧
free -m命令监控内存使用,确保物理内存充足(如16GB及以上用于生产环境)。ufw disable)、禁用SELinux(setenforce 0)等,减少系统负载。echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
nofile设为65536),避免高并发时连接数受限。/etc/mongod.conf,设置storage.wiredTiger.engineConfig.cacheSizeGB为系统内存的50%-70%(如4GB内存设为2-3GB),平衡缓存利用率与系统稳定性。operationProfiling部分添加:operationProfiling:
mode: slowOp
slowOpThresholdMs: 100 # 记录执行时间超过100ms的查询
通过db.setProfilingLevel(2)实时开启慢查询日志,用db.system.profile.find()分析慢查询。net.maxIncomingConnections(如设为1000),避免过多连接导致资源耗尽;设置net.port为非默认端口(如27018),提升安全性。userid、timestamp)创建索引,使用db.collection.createIndex({field: 1})(1表示升序)。复合索引适用于多字段查询(如db.collection.createIndex({field1: 1, field2: -1}),-1表示降序)。db.collection.find({field1: value}, {field1: 1, _id: 0}))。db.collection.reIndex()重建碎片化索引;通过db.collection.stats()分析索引大小,删除不再使用的索引(如db.collection.dropIndex("index_name"))。explain("executionStats")查看查询计划,确认索引是否被命中(winningPlan.inputStage.stage应为IXSCAN)。db.users.find({age: {$gt: 18}}, {name: 1, age: 1, _id: 0}))。skip()和limit()分批获取数据(如db.users.find().skip(20).limit(10)),避免一次性加载大量数据。insertMany()、updateMany()替代单条操作,减少网络往返次数。db.collection.find({field: value}).hint({field: 1})强制使用索引)。replication:
replSetName: "rs0"
初始化副本集:rs.initiate()。userid),避免热点问题。mongostat监控每秒操作数(如读、写、查询)、mongotop查看集合级读写时间,快速定位性能瓶颈。/var/log/mongodb/mongod.log)中的错误与警告信息,及时处理异常。