MongoDB的性能调优需结合硬件配置、操作系统优化、MongoDB自身配置、索引与查询优化、架构设计及监控等多层面进行。以下是针对CentOS系统的具体方法:
硬件是性能基础,需优先满足以下要求:
/etc/security/limits.conf,添加以下内容:mongod soft nofiles 64000
mongod hard nofiles 64000
mongod soft nproc 64000
mongod hard nproc 64000
同时,通过sysctl命令调整内核参数(如fs.file-max):sudo sysctl -w fs.file-max=100000
/etc/fstab,在挂载项中添加noatime参数(如/dev/xvdb /data ext4 noatime 0 0),然后重新挂载:sudo mount -o remount /data
echo never | sudo tee /proc/sys/vm/transparent_hugepage/enabled
echo never | sudo tee /proc/sys/vm/transparent_hugepage/defrag
(需将上述命令添加到/etc/rc.local中,实现开机自动禁用)。编辑/etc/mongod.conf(默认路径),调整以下关键参数:
storage:
  engine: wiredTiger
  wiredTiger:
    engineConfig:
      cacheSizeGB: 8  # 根据服务器内存调整,如8GB内存可分配6~7GB给WiredTiger
net:
  port: 27017
  bindIp: 0.0.0.0  # 允许远程访问(生产环境需限制IP)
  maxIncomingConnections: 5000  # 最大连接数
  socketOptions:
    keepAlive: 1    # 启用TCP keepalive
    tcpNoDelay: true  # 禁用Nagle算法,减少延迟
operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 100
replication:
  journal:
    commitIntervalMs: 100  # 可适当调整为50~200ms
user_id、created_at)创建索引:db.collection.createIndex({ field1: 1 });  // 1表示升序,-1表示降序
{ user_id: 1, created_at: -1 }),避免单字段索引的多次查找;db.collection.stats()查看索引使用率,删除未使用的索引。db.collection.find({ field: value }, { field1: 1, _id: 0 });  // 不返回_id字段
var bulk = db.collection.initializeUnorderedBulkOp();
bulk.insert({ name: "Alice", age: 25 });
bulk.insert({ name: "Bob", age: 30 });
bulk.execute();
explain("executionStats")分析查询执行计划,确保查询使用了索引:db.collection.find({ field: value }).explain("executionStats");
compact命令压缩集合,回收碎片空间(需停机或锁定集合):db.runCommand({ compact: 'collection_name' });
mongodump),防止数据丢失。systemLog:
  destination: file
  path: /var/log/mongodb/mongod.log
  logAppend: true
  logRotate: reopen  # 通过logrotate工具实现自动轮转
mongostat查看操作速率、mongotop查看集合级IO)实时监控性能;以上方法需根据实际业务场景(如数据量、并发量、查询模式)灵活调整,建议在调整前备份数据,并通过监控工具验证优化效果。