How to reduce MongoDB storage space after deleting large amount of data?

To reduce MongoDB storage space after deleting a large amount of data, you need to reclaim the freed disk space since MongoDB doesn't automatically release space after deletions. The database continues to use the same amount of disk space even after documents are removed.

Syntax

db.runCommand({ "compact": "collectionName" })

Or for the entire database:

db.repairDatabase()

Method 1: Using compact Command (Recommended)

The compact command is the modern approach to reclaim space from a specific collection ?

db.runCommand({ "compact": "users" })
{ "ok" : 1, "bytesFreed" : 1048576 }

Method 2: Using repairDatabase()

Check current database and repair the entire database to reclaim space ?

db
test
db.repairDatabase()
{ "ok" : 1 }

Key Differences

Method Scope Downtime Use Case
compact Single collection Collection-level lock Targeted space reclaim
repairDatabase Entire database Database-level lock Full database cleanup

Conclusion

Use compact for individual collections or repairDatabase() for entire database cleanup. Both commands reclaim disk space by removing fragmentation and unused space left after deletions.

Updated on: 2026-03-15T00:33:00+05:30

558 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements