ITPub博客

首页 > 数据库 > NoSQL > MongoDB服务端JavaScript脚本使用方法

MongoDB服务端JavaScript脚本使用方法

NoSQL 作者:chenfeng 时间:2017-03-22 10:41:59 0 删除 编辑
常用JavaScript语句

db.getSiblingDB(<dbname>)   
db.getCollectionNames()    
db.getCollection(<collname>)    
db.printCollectionStats()
在mongo shell运行JavaScript脚本

切换数据库:  
use <dbname>
运行如下脚本:

var total = 0;
var dbaStatCollections = function(){};
 
dbaStatCollections = function(){
  collNames = db.getCollectionNames();
  for (var index = 0; index < collNames.length; index++) {
    var coll = db.getCollection(collNames[index]); 
    var stats = coll.stats();
    print('ns,count,size,totalIndexSize');
  print(stats.ns + ',' + stats.count + ',' + stats.size + ',' + stats.totalIndexSize);
  }
}
 
dbaStatCollections();
可将上述脚本保存为dbaStatCollections.js, 


在linux shell下运行  

mongo localhost:27017/<dbname> dbaStatCollections.js
或在mongo shell下运行    

load("dbaStatCollections.js")
在服务端存储JavaScript函数

db.system.js.remove({"_id":"dbaStatCollections"});
 
db.system.js.save(   
{
  _id : "dbaStatCollections" ,
  value : function () {
    collNames = db.getCollectionNames();
    for (var index = 0; index < collNames.length; index++) {
      var coll = db.getCollection(collNames[index]);
      var stats = coll.stats();
      print('ns,count,size,totalIndexSize');
      print(stats.ns + ',' + stats.count + ',' + stats.size + ',' + stats.totalIndexSize);
    }
  }
}
);
 
db.loadServerScripts();
 
dbaStatCollections();
在当前JavaScript上下文中,可以使用该函数。退出该会话后,该函数不会被保存。只可在Primary执行。


备注:以上输出结果保存为CSV文件打开。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/15498/viewspace-2135804/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
交流MySQL,PolarDB/PolarDB-X,PostgreSQL,MongoDB和Redis技术。

注册时间:2015-12-07

  • 博文量
    784
  • 访问量
    2691669