debian

Debian系统MongoDB如何调优

小樊
41
2025-08-12 08:12:04
栏目: 云计算

Debian系统MongoDB调优指南

一、基础配置优化

  1. 安装与配置文件

    • 使用64位版本以支持更大内存映射。
    • 编辑 /etc/mongod.conf
      • 绑定IP:net.bindIp: 0.0.0.0(允许远程访问,生产环境需限制)。
      • 端口:net.port: 27017(默认端口,可自定义)。
      • 数据目录:storage.dbPath 指向高性能存储路径(如SSD)。
  2. 存储引擎优化

    • 使用WiredTiger引擎(默认),设置缓存大小为系统内存的50%-80%:
      storage.wiredTiger.engineConfig.cacheSizeGB: 4(根据服务器内存调整)。
    • 启用压缩:storage.wiredTiger.collectionConfig.blockCompressor: snappy

二、索引与查询优化

  1. 索引策略

    • 为高频查询字段创建单字段索引:db.collection.createIndex({ field: 1 })
    • 多字段查询使用复合索引:db.collection.createIndex({ field1: 1, field2: 1 })
    • 避免过度索引,定期用 db.collection.aggregate([{indexStats: {}}]) 清理未使用索引。
  2. 查询优化

    • 使用投影限制返回字段:db.collection.find({}, { field1: 1, field2: 1 })
    • explain("executionStats") 分析查询计划,避免全表扫描。

三、硬件与部署优化

  1. 硬件选择

    • 使用SSD替代HDD,提升I/O性能。
    • 增加内存,确保常用数据可缓存。
  2. 高可用与扩展

    • 配置副本集提升读性能:rs.initiate() 并设置 readPreference: secondaryPreferred
    • 大数据集采用分片(Sharding):sh.enableSharding("db") + sh.shardCollection("db.collection", { shardKey: 1 })

四、监控与维护

  1. 实时监控

    • 使用 mongostat 监控QPS、连接数等指标。
    • mongotop 查看热点集合的读写情况。
  2. 日志与调优

    • 启用慢查询日志:systemLog.slowQueryThresholdMs: 100(单位:毫秒)。
    • 定期执行 compact 命令回收空间,避免碎片堆积。

五、其他技巧

注意:每次修改配置后需重启MongoDB服务:sudo systemctl restart mongod

参考来源:

0
看了该问题的人还看了