在Mongo Shell中執(zhí)行以下腳本,直接計算并打印每個集合的大?。▎挝籑B):
// 切換到目標數(shù)據(jù)庫
use test;
// 遍歷所有集合并統(tǒng)計大小
db.getCollectionNames().forEach(function(collName) {
// 獲取集合的統(tǒng)計信息
var stats = db.getCollection(collName).stats();
// 計算集合總大小(數(shù)據(jù) + 索引)
var totalSizeMB = (stats.storageSize + stats.totalIndexSize) / (1024 * 1024);
// 打印結果(保留兩位小數(shù))
print(collName + ": " + totalSizeMB.toFixed(2) + " MB");
});
如果無法直接運行腳本,可手動查詢每個集合的統(tǒng)計信息:
// 1. 列出所有集合名稱
show collections;
// 2. 對每個集合分別執(zhí)行(以 callLog 為例)
db.callLog.stats();

image.png
在Mongo Shell中執(zhí)行以下腳本,直接計算并打印每個集合的大小(單位GB):
// 切換到目標數(shù)據(jù)庫
use test;
print("數(shù)據(jù)庫中各集合大小統(tǒng)計(GB):");
print("======================================");
// 獲取所有集合名稱并遍歷
db.getCollectionNames().forEach(function(collName) {
try {
// 獲取集合統(tǒng)計信息
var stats = db.getCollection(collName).stats();
// 計算總大?。〝?shù)據(jù) + 索引)并轉換為GB
var totalSizeGB = (stats.storageSize + stats.totalIndexSize) / (1024 * 1024 * 1024);
// 打印結果(保留4位小數(shù))
print(collName.padEnd(25) + ": " + totalSizeGB.toFixed(4) + " GB");
} catch (e) {
print("無法獲取集合 " + collName + " 的統(tǒng)計信息: " + e);
}
});
print("======================================");
// 添加數(shù)據(jù)庫總大小統(tǒng)計
var dbStats = db.stats();
var dbTotalSizeGB = (dbStats.storageSize + dbStats.totalIndexSize) / (1024 * 1024 * 1024);
print("數(shù)據(jù)庫總大小: " + dbTotalSizeGB.toFixed(4) + " GB");
使用說明:
- 執(zhí)行方式:
mongo --quiet your_mongodb_uri check_size_script.js
- 輸出示例:
數(shù)據(jù)庫中各集合大小統(tǒng)計(GB):
======================================
callLog: 0.1250 GB
======================================
數(shù)據(jù)庫總大小: 2.7304 GB
關鍵特性:
- 單位轉換:自動將字節(jié)轉換為GB(1 GB = 10243 字節(jié))
- 異常處理:捕獲無法訪問的集合(如系統(tǒng)集合)
- 格式化輸出:
- 集合名稱左對齊(25字符寬度)
- 大小值保留4位小數(shù)
- 額外統(tǒng)計:包含數(shù)據(jù)庫總大小匯總
-
安全執(zhí)行:使用
try-catch防止單個集合錯誤中斷整個腳本
注意事項:
- 需要至少對目標數(shù)據(jù)庫有
read權限 - 統(tǒng)計的是磁盤空間占用(包含預分配空間和索引),非數(shù)據(jù)實際大小
- 大型集合統(tǒng)計可能耗時較長(腳本會等待所有集合統(tǒng)計完成)
- 系統(tǒng)集合(如
system.*)可能因權限問題無法統(tǒng)計
提示:如需更精確的集合數(shù)據(jù)大?。ú缓A分配空間),可將
storageSize替換為size字段,但這會反映實際數(shù)據(jù)大小而非磁盤占用。