温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

MongoDB服务端JavaScript脚本

发布时间:2020-06-23 06:39:39 来源:网络 阅读:4166 作者:UltraSQL 栏目:MongoDB数据库

MongoDB服务端JavaScript脚本

 

常用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文件打开。


在mongo shell启动配置文件.mongorc.js中存储JavaScript函数


mongodb shell默认会加载~/.mongorc.js文件,可以自定义prompt变量来修改shell提示信息。也可以将上述常用的DBA管理函数放到这里。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI