Common Commands in MongoDB
Check Size of Tables in a Database
To check the size of tables in a database, use the following command to access the desired database:
use database_name
- Replace the database_name with the actual name of the database you want to access, for example:
use mdworkflow
.
(() => {
const getReadableSize = b => b === 0 ? '0.0 B' :
((u=['B','kB','MB','GB','TB','PB'])[i=Math.floor(Math.log(b)/Math.log(1024))],
`${(b/Math.pow(1024,i)).toFixed(1)} ${u[i]}`);
const stats = db.getCollectionNames().map(n => {
try {
const s = db.getCollection(n).stats();
return {
ns: s.ns || `${db.getName()}.${n}`,
count: s.count || 0,
size: (s.storageSize || 0) + (s.totalIndexSize || 0)
};
} catch (e) { return null; }
}).filter(s => s && s.size > 0).sort((a,b) => b.size - a.size);
if (!stats.length) return print("No valid collection data");
const [maxNs, maxCnt] = stats.reduce(([nl, cl], s) => [
Math.max(nl, s.ns.length),
Math.max(cl, s.count.toString().length)
], ['Collection'.length, 'Documents'.length]);
const h = `Collection${' '.repeat(maxNs-10)} | Documents${' '.repeat(maxCnt-9)} | Total Size`;
print(h + '\n' + '-'.repeat(h.length));
stats.forEach(s => print(
`${s.ns.padEnd(maxNs)} | ${s.count.toString().padEnd(maxCnt)} | ${getReadableSize(s.size)}`
));
})();
- After running the above command, it will display the size of tables in the current database.