常用JavaScript语句
1
2
3
4
|
db.getSiblingDB(<dbname>)
db.getCollectionNames()
db.getCollection(<collname>)
db.printCollectionStats()
|
在mongo shell运行JavaScript脚本
切换数据库:
1
|
use <dbname>
|
运行如下脚本:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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下运行
1
|
mongo localhost:27017/<dbname> dbaStatCollections.js
|
或在mongo shell下运行
1
|
load(
"dbaStatCollections.js"
)
|
在服务端存储JavaScript函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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文件打开。
在mongo shell启动配置文件.mongorc.js中存储JavaScript函数
mongodb shell默认会加载~/.mongorc.js文件,可以自定义prompt变量来修改shell提示信息。也可以将上述常用的DBA管理函数放到这里。
本文转自UltraSQL51CTO博客,原文链接: http://blog.51cto.com/ultrasql/1705153,如需转载请自行联系原作者