mongo shell启动配置文件.mongorc.js(三)

自定义MongoDB操作函数


可以把自己写的js代码保存在某个地方,让MongoDB加载它,然后就可以在MongoDB的命令行里操作它们。


mongodb shell默认会加载~/.mongorc.js文件


例如以下修改了启动提示文字、左侧提示文字,增加了my_show_shards shell函数用于显示当前sharded collection的chunks在各分片的负载情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//~/.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());    
                })    
            })    
}












本文转自UltraSQL51CTO博客,原文链接: http://blog.51cto.com/ultrasql/1707354,如需转载请自行联系原作者










评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值