MongoDB在Linux中的性能调优技巧
storage.wiredTiger.engineConfig.cacheSizeGB设置为服务器物理内存的50%-70%(需预留足够内存给系统和其他进程)。例如,在/etc/mongod.conf中配置:storage:
wiredTiger:
engineConfig:
cacheSizeGB: 4 # 根据服务器内存调整,如16GB内存可设为8GB
vm.swappiness(默认60):减少系统使用交换空间(Swap)的倾向,避免内存不足时频繁换页导致性能下降。设置为10或更低(sysctl -w vm.swappiness=10),并添加到/etc/sysctl.conf持久化。vm.overcommit_memory=1(允许内存超额分配,但需避免过度使用),同样添加到/etc/sysctl.conf。dbpath)部署在SSD上。-b size=4096)。挂载时添加noatime选项(减少文件访问时间更新):mount -o noatime /dev/sdb1 /var/lib/mongodb
find、sort、aggregate等操作中频繁使用的字段创建索引。例如,为用户集合的username字段创建单字段索引:db.users.createIndex({ username: 1 });
{status: "active", age: {$gt: 18}}),创建复合索引并将选择性高的字段放在前面(选择性高的字段能过滤更多数据)。例如:db.users.createIndex({ status: 1, age: 1 }); // status选择性更高
db.collection.getIndexes()查看索引数量,删除未使用的索引(通过$indexStats分析)。find({username: "john"}, {username: 1, _id: 0})),避免访问实际文档,减少I/O。db.users.find({}, { username: 1, email: 1, _id: 0 }); // 仅返回username和email
limit()减少返回的文档数,避免一次性传输大量数据。例如:db.users.find().limit(10); // 只返回前10条
explain()分析查询计划,确保查询使用了索引。若executionStats.executionStages.stage显示为COLLSCAN(全表扫描),需优化索引。例如:db.users.find({ username: "john" }).explain("executionStats");
bulkWrite),减少网络往返次数,提高吞吐量。net.port(默认27017)和net.maxIncomingConnections(默认65536,可根据并发连接数调整,如10000)。例如:net:
port: 27017
maxIncomingConnections: 10000
operationProfiling.mode: slowOp)并设置慢查询阈值(如100ms),定期分析慢查询日志优化性能:operationProfiling:
mode: slowOp
slowOpThresholdMs: 100
replication.replSetName配置副本集(如rs0),提高数据可用性和读取性能(可将读请求分发到从节点)。user_id)将数据分散到多个分片,提高写入和查询的横向扩展能力。mongostat(监控操作速率,如读/写次数、延迟)和mongotop(监控集合级别的读/写时间)实时查看性能指标。例如:mongostat --host localhost --port 27017
mongotop --host localhost --port 27017
db.collection.reIndex()重建碎片化索引,提升查询效率。mongodump和mongorestore定期备份,避免数据丢失。