MongoDB Drop All Empty Collections

Published by Hendry Sadrak
Posted on

A short script to drop all empty collections in MongoDB or a compatible database like AWS DocumentDB or Azure CosmosDB:

// list all databases
let dbs = db.adminCommand({
  listDatabases: 1,
}).databases

dbs.forEach(({ name: dbName }) => {
  // skip internal databases
  if (dbName === 'admin' || dbName === 'config' || dbName === 'local') return

  db = db.getSiblingDB(dbName)

  // list all collections
  db.getCollectionNames().forEach(coll => {
    let count = db[coll].countDocuments()

    // if no docs go ahead and drop
    if (count === 0) {
      print(dbName, coll, 'is empty, dropping.')

      db[coll].drop()
    }
  })
})