MongoDB服务端JavaScript脚本使用方法
常用JavaScript语句
db.getSiblingDB(<dbname>) db.getCollectionNames() db.getCollection(<collname>) db.printCollectionStats()
在mongoshell运行JavaScript脚本
切换数据库:
use<dbname>
运行如下脚本:
vartotal=0;
vardbaStatCollections=function(){};
dbaStatCollections=function(){
collNames=db.getCollectionNames();
for(varindex=0;index<collNames.length;index++){
varcoll=db.getCollection(collNames[index]);
varstats=coll.stats();
print('ns,count,size,totalIndexSize');
print(stats.ns+','+stats.count+','+stats.size+','+stats.totalIndexSize);
}
}
dbaStatCollections();
可将上述脚本保存为dbaStatCollections.js,
在linuxshell下运行
mongolocalhost:27017/<dbname>dbaStatCollections.js
或在mongoshell下运行
load("dbaStatCollections.js")
在服务端存储JavaScript函数
db.system.js.remove({"_id":"dbaStatCollections"});
db.system.js.save(
{
_id:"dbaStatCollections",
value:function(){
collNames=db.getCollectionNames();
for(varindex=0;index<collNames.length;index++){
varcoll=db.getCollection(collNames[index]);
varstats=coll.stats();
print('ns,count,size,totalIndexSize');
print(stats.ns+','+stats.count+','+stats.size+','+stats.totalIndexSize);
}
}
}
);
db.loadServerScripts();
dbaStatCollections();
在当前JavaScript上下文中,可以使用该函数。退出该会话后,该函数不会被保存。只可在Primary执行。
备注:以上输出结果保存为CSV文件打开。
本文出自“SQLServerDeepDives”博客