mongo 查看某个库下面每个集合的大小

查看集合大小

show dbs;
[root@ip ~]# cat get_size.sh 
#!/bin/sh

MONGO=/usr/bin/mongo

function get_dbs() {
  $MONGO << EOF
show dbs
EOF
}

function get_tables() {
    # $1 is dbname
    DB=$1
    $MONGO  << EOF
use $DB ;
show tables;
EOF
}

function get_a_table_size() {
  DB=$1
  TABLE=$2
  $MONGO  << EOF
use $DB ;
db.$TABLE.totalSize()
EOF
}

function get_size() {
  for i in `get_tables $1 |head -n -1 |tail -n +5`
    do
      SIZE=`get_a_table_size $1 $i |sed -n 5p`
     echo "$SIZE $i"
    done
}
echo $1
get_size $1 | tail -n +2 | sort -r -n | awk '{size=$1/1024;if(size<1024){printf("%10.3f KB\t%s\n",size,$2);}else{size=size/1024;if(size<1024){printf("\033[36m%10.3f MB\t%s\n\033[0m",size,$2);}else{size=size/1024;if(size<1024){printf("\033[35m%10.3f GB\t%s\n\033[0m",size,$2);}else{size=size/1024;printf("\033[31m%10.3f TB\t%s\n\033[0m",size,$2);}}}}'

第二种方式

cat getsize.js

db = connect("mongodb://ip:27017/default")

var collectionNames= db.getCollectionNames();
for (var i = 0; i < collectionNames.length; i++) {     
  var coll = db.getCollection(collectionNames[i]);   
  var stats = coll.stats(1024 * 1024);   
  print(stats.ns, stats.storageSize);
}

mongo getsize.js
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 `MongoTemplate` 的 `executeCommand()` 方法执行 MongoDB 的 `dbStats` 命令来获取集合表空间大小。 示例代码如下: ```java MongoOperations mongoOps = new MongoTemplate(new MongoClient("localhost"), "testdb"); CommandResult result = mongoOps.executeCommand("{ dbStats: 1, scale: 1024 }"); DBObject obj = (DBObject) result.get("collections"); for (String collectionName : obj.keySet()) { DBObject collectionStats = (DBObject) obj.get(collectionName); double size = Double.parseDouble(collectionStats.get("size").toString()); double storageSize = Double.parseDouble(collectionStats.get("storageSize").toString()); double totalIndexSize = Double.parseDouble(collectionStats.get("totalIndexSize").toString()); double indexSizes = Double.parseDouble(collectionStats.get("indexSizes").toString()); double fileSize = Double.parseDouble(collectionStats.get("fileSize").toString()); System.out.println("Collection: " + collectionName); System.out.println("Size: " + size / 1024 + " KB"); System.out.println("Storage Size: " + storageSize / 1024 + " KB"); System.out.println("Total Index Size: " + totalIndexSize / 1024 + " KB"); System.out.println("Index Sizes: " + indexSizes / 1024 + " KB"); System.out.println("File Size: " + fileSize / 1024 + " KB"); } ``` 上述代码中,`dbStats` 命令返回的结果包含了所有集合的统计信息。你可以遍历结果中的每一个集合,然后获取其表空间大小等信息。在上述代码中,我们将表空间大小等信息输出到控制台。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值