After deleting data in MongoDB, how to reclaim disk space using the compact comm

2023. 3. 15. 08:44mongodb

반응형



Recently, while monitoring MongoDB, I was reminded of the importance of DML (Data Manipulation Language) - the ability to query (SELECT), modify (UPDATE), store (INSERT), and delete (DELETE) data.

I had a surprising issue with MongoDB: after deleting data, the disk space was not being returned. The disk usage of our MongoDB server had reached 78%, and the MongoDB development server, which hadn't been in use for even three months, was full. The design was meant to store data for more than a year, so I felt that something was not right.

728x90


I conducted various tests and found that when I dropped the collection, the disk space decreased, but when I deleted the collection, the disk space remained the same. This was alarming because deleting data should have returned the disk space.

After researching the issue, I discovered the "compact" command. It's like defragmentation for the disk - a command that cleans up unused data and returns the space to be used. The effect of the command was remarkable; the disk usage dropped from 78% to 36%. Since our development server had many incorrectly used and deleted data, the impact of this command was particularly significant.

반응형

1. First, access the database.

use database_name


2. Select the collection you want to compact.

db.runCommand( {compact : Collection_name, force : true} )

3. And then anxiously wait...

Fortunately, no collection lock was applied during my tests, and even when I ran the command on the production server, there were no major issues. However, the waiting time was quite nerve-wracking.

In reality, the "compact" command is not a perfect solution for storage capacity. According to various articles, the best approach is to migrate the data to a new server. It is a time-consuming and complicated task that may not be recommended for all environments, but it's worth considering if your company or environment supports it.

Overall, while managing MongoDB, I took some time to reflect on the importance of DML and how critical it is to handle data properly.


반응형