Skip to content

Instantly share code, notes, and snippets.

@wencan
Created December 21, 2015 06:14
Show Gist options
  • Save wencan/6a30b807cec187f3757b to your computer and use it in GitHub Desktop.
Save wencan/6a30b807cec187f3757b to your computer and use it in GitHub Desktop.
mongodb数据库和所有集合的磁盘空间使用情况
#!/usr/bin/env node
var mongodb = require("mongodb")
, async = require("async")
, argv = require('minimist')(process.argv.slice(2))
, table = require("cli-table")
;
var mongo_url = argv.mongodb || 'mongodb://127.0.0.1/test';
function db_stats(db, callback) {
db.stats(function(err, stats){
stats = stats || {}
callback(err, {
'collections': stats.collections,
'objects': stats.objects,
'dataSize': Math.round(stats.dataSize/1024/1024/1024*100)/100 + 'GB',
'storageSize': Math.round(stats.storageSize/1024/1024/1024*100)/100 + 'GB',
'indexes': stats.indexes,
'indexSize': Math.round(stats.indexSize/1024/1024/1024*100)/100 + 'GB',
'fileSize': Math.round(stats.fileSize/1024/1024/1024*100)/100 + 'GB'
})
})
}
function collection_stats(collection, callback) {
collection.stats(function(err, stats){
stats = stats || {}
callback(err, {
'name': collection.collectionName,
'count': ''+stats.count,
'size': Math.round(stats.size/1024/1024/1024*100)/100 + 'GB',
'storageSize': Math.round(stats.storageSize/1024/1024/1024*100)/100 + 'GB',
'nindexes': ''+stats.nindexes,
'totalIndexSize': Math.round(stats.totalIndexSize/1024/1024/1024*100)/100 + 'GB'
})
})
}
function collections_stats(db, callback) {
//node-mongodb-native的collections、listCollections实现有问题
db.command({listCollections: 1}, function(err, result){
if(err) return console.log(err)
async.map(result.cursor.firstBatch, function(item, callback){
var collection = db.collection(item.name)
collection_stats(collection, callback)
}, callback)
})
}
mongodb.MongoClient.connect(mongo_url, function(err, db){
if(err) return console.log(err)
async.series([
function(callback) {
db_stats(db, function(err, stats){
if(err) return callback(err)
var form = new table({
head: Object.keys(stats)
})
form.push(Object.keys(stats).map(function(key){
return stats[key]
}))
console.log(form.toString())
callback(null)
})
},
function(callback) {
collections_stats(db, function(err, statss){
if(err) return callback(err)
if(statss.length==0) return callback()
var form = new table({
head: Object.keys(statss[0])
})
statss.map(function(stats){
form.push(Object.keys(stats).map(function(key){
return stats[key]
}))
})
console.log(form.toString())
callback(null)
})
}
], function(err){
if(err) return console.log(err);
db.close()
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment