安装与配置文件
/etc/mongod.conf
:
net.bindIp: 0.0.0.0
(允许远程访问,生产环境需限制)。net.port: 27017
(默认端口,可自定义)。storage.dbPath
指向高性能存储路径(如SSD)。存储引擎优化
storage.wiredTiger.engineConfig.cacheSizeGB: 4
(根据服务器内存调整)。storage.wiredTiger.collectionConfig.blockCompressor: snappy
。索引策略
db.collection.createIndex({ field: 1 })
。db.collection.createIndex({ field1: 1, field2: 1 })
。db.collection.aggregate([{indexStats: {}}])
清理未使用索引。查询优化
db.collection.find({}, { field1: 1, field2: 1 })
。explain("executionStats")
分析查询计划,避免全表扫描。硬件选择
高可用与扩展
rs.initiate()
并设置 readPreference: secondaryPreferred
。sh.enableSharding("db")
+ sh.shardCollection("db.collection", { shardKey: 1 })
。实时监控
mongostat
监控QPS、连接数等指标。mongotop
查看热点集合的读写情况。日志与调优
systemLog.slowQueryThresholdMs: 100
(单位:毫秒)。compact
命令回收空间,避免碎片堆积。insertMany
替代单条插入,减少网络开销。注意:每次修改配置后需重启MongoDB服务:sudo systemctl restart mongod
。
参考来源: