I want to calculate free storage size of my mongoDB collection

I want to calculate free storage size of my mongoDB collection and if the free space is less than 90%, I would like to delete first 100 records. I am finding best way to know the available free space in (%) percentage for my collection or complete DB.

I am currently using below which seems not correct to me.

mongoose.connection.db.stats().then(async statResp => {
if (statResp?.fsTotalSize && statResp?.fsUsedSize) {
let usedSpace = ((statResp.fsTotalSize - statResp.fsUsedSize) / statResp.fsTotalSize) * 100;

Hi @Sankalp_Karakoti

If you want a fixed sized collection then a Capped Collection is recommended.

fsTotalSize and fsUsedSize are the same as what would be visible from looking at the volume’s Free Size using OS level tools.

For collection specific information collStats would need to be used to get totalSize.

Even then deleting documents from the collection will not free any storage back to the OS, at best it will just mark blocks free in the collection to be reused. In which case a capped collection is still a better option.

@chris - So isn’t there a way to know if my mongo DB is getting full? How do I know my DB allocated storage is about to be full so that I can take some action from my codebase?

@Sankalp_Karakoti I wrote about this a few years ago at Identifying and Reclaiming Disk Space in MongoDB | ALEX BEVILACQUA.

There might be some info there that can help you understand your collection(s) disk usage, but ultimately to identify if your “MongoDB database is getting full” there are Alerts for Free Tier Clusters or Dedicated Clusters you can configure.