默认情况下,所有数据库的数据文件都存放在dbPath指定的目录下。
当实例中数据库较多的时候,目录就会比较乱。 所以在生产环境,建议配置每个DB使用独立的目录。
配置参数是:storage.directoryPerDB,该值默认为false。
当设置为true后,会在storage.dbPath 参数指定的目录下,为每个库使用独立的子目录。
For standalone instances
Use mongodump on the existing mongod instance to generate a backup.
Stop the mongod instance.
Add the storage.directoryPerDB value and configure a new data directory
Restart the mongod instance.
Use mongorestore to populate the new data directory.
For replica sets:
Stop a secondary member.
Add the storage.directoryPerDB value and configure a new data directory to that secondary member.
Restart that secondary.
Use initial sync to populate the new data directory.
Update remaining secondaries in the same fashion.
Step down the primary, and update the stepped-down member in the same fashion.
注意这里,第二步,需要指定新的路径,或者对原路径进行重命名备份,否则当参数改成true以后,实例无法启动,会报如下错误:
{"t":{"$date":"2022-05-07T14:27:13.884+08:00"},"s":"E", "c":"STORAGE", "id":20557, "ctx":"initandlisten","msg":"DBException in initAndListen, terminating","attr":{"error":"InvalidOptions: Requested option conflicts with current storage engine option for directoryPerDB; you requested true but the current server storage is already set to false and cannot be changed"}}
操作示例:
1.关闭shard1 库,并修改参数。
[root@testdb shard1]# supervisorctl stop shard1
shard1: stopped
2.备份旧目录:
[root@testdb data]# mv shard1 shard1_bak
[root@testdb data]# mkdir shard1
[root@testdb etc]# cat shard1.conf
……
storage:
journal:
enabled: true
dbPath: "/data/mongodb/data/shard1"
oplogMinRetentionHours: 150
directoryPerDB: true
……
[root@testdb etc]#
[root@testdb data]# supervisorctl start shard1
shard1: started
3.同步数据
MongoDB 启动会自动同步,如果库比较大,同步时间会比较长,因为需要调整oplog的大小,保证oplog 保留数据的时间大于同步需要的时间。
然后逐个在其他secondary节点上进行操作,Primary 节点要先进行step-down 降级之后再处理。
生产环境在线变更还是有一定影响,最好的方法就是上线之前就配置好参数。