1. 前言
mongodb文档中存储一节中关于磁盘空间回收的说明,简单处理、备注记于此。标号为另加,原文档见:https://docs.mongodb.com/v3.2/faq/storage/
2. Why are the files in my data directory larger than the data in my database?
2.1 ...(省略3节,关于预分配空间、oplog、journal)
2.2 Empty records
MongoDB maintains lists of empty records in data files as it deletes documents and collections. MongoDB can reuse this space, but will not, by default, return this space to the operating system.
To allow MongoDB to more effectively reuse the space, you can de-fragment your data. To de-fragment, use the compact command. The compact requires up to 2 gigabytes of extra disk space to run. Do not use compact if you are critically low on disk space. For more information on its behavior and other considerations, see compact.
compact only removes fragmentation from MongoDB data files within a collection and does not return any disk space to the operating system. To return disk space to the operating system, see How do I reclaim disk space?.
2.3 按
上文提到可通过compact命令处理空记录导致的fragmentation,说这并不会向OS返还磁盘空间;但查询文档发现如果采用的是WiredTriger存储引擎,这部分磁盘空间是被返还给OS的;另外compact的用法是:
db.yourCollection.runCommand("compact");
或
db.runCommand({ compact : 'yourCollection' });
3. How do I reclaim disk space?
The following provides some options to consider when reclaiming disk space.
NOTE
You do not need to reclaim disk space for MongoDB to reuse freed space. See Empty records for information on reuse of freed space.
3.1 repairDatabase
You can use repairDatabase on a database to rebuilds the database, de-fragmenting the associated storage in the process.
repairDatabase requires free disk space equal to the size of your current data set plus 2 gigabytes. If the volume that holds dbpath lacks sufficient space, you can mount a separate volume and use that for the repair. For additional information and considerations, see repairDatabase.
WARNING
Do not use repairDatabase if you are critically low on disk space.
repairDatabase will block all other operations and may take a long time to complete.
You can only run repairDatabase on a standalone mongod instance.
You can also run the repairDatabase operation for all databases on the server by restarting your mongod standalone instance with the --repair and --repairpath options. All databases on the server will be unavailable during this operation.
3.2 按
运行compact命令需要至少2G的磁盘空间,repairDatabase需要的磁盘空间则与数据库大小有关,若数据库为x,则需要至少预留x+2。