mongo shell启动配置文件.mongorc.js(三)
自定义MongoDB操作函数
可以把自己写的js代码保存在某个地方,让MongoDB加载它,然后就可以在MongoDB的命令行里操作它们。
mongodb shell默认会加载~/.mongorc.js文件
例如以下修改了启动提示文字、左侧提示文字,增加了my_show_shards shell函数用于显示当前sharded collection的chunks在各分片的负载情况:
//~/.mongorc.js
//show at begin
var compliment = ["attractive", "intelligent", "like batman"];
var index = Math.floor(Math.random()*3);
print("Hello, you're looking particularly " + compliment[index] + " today!");
//change the prompt
prompt = function(){
if (typeof db == "undefined") {
return "(nodb)> ";
}
// Check the last db operation
try {
db.runCommand({getLastError: 1});
}
catch (e) {
print(e);
}
return db + "> ";
}
//show all shard's chunks
function my_show_shards() {
var config_db = db.getSiblingDB("config");
var collections = {};
var shards = {};
var shard_it = config_db.chunks.find().snapshot();
while (shard_it.hasNext()) {
next_item = shard_it.next();
collections[JSON.stringify(next_item["ns"]).replace(/\"/g, "")] = 1;
shards[JSON.stringify(next_item["shard"]).replace(/\"/g, "")] = 1;
}
var list_collections = [];
var list_shards = [];
for (item in collections) {
list_collections.push(item);
}
for (item in shards) {
list_shards.push(item);
}
list_collections.forEach(function(collec) {
list_shards.forEach(function(item) {
obj = {};
obj["shard"] = item;
obj["ns"] = collec;
it = config_db.chunks.find(obj);
print(collec, item, it.count());
})
})
}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。