MongoDB:.mongorc.js中定义的自定义命令

时间:2016-09-06 19:32:35

标签: mongodb mongodb-shell

我想定义一个自定义的Mongo shell命令。鉴于var dbuc; (function () { dbuc = (function () { return db.getName().toUpperCase(); })(); })(); 如下所示:

> db
test
> dbuc
TEST

> use otherbase

> db
otherbase
> dbuc
TEST

我为初始数据库获得了正确的大写名称,但是当我切换到其他数据库时,我仍然得到初始数据库的名称而不是当前数据库的名称。

.mongorc.js

我看到mongodbuc运行之前运行,这就是为什么www.omdbapi.com变量已赋予初始数据库 - 测试值的原因。但我不知道如何获得当前数据库的名称,无论我打开什么基础。

1 个答案:

答案 0 :(得分:1)

有几点需要注意:

  • 在mongo shell中,typeof db是一个javascript对象,typeof dbuc是字符串。
  • 我相信,在您的代码中,dbuc值已分配一次,并且在调用use时不会更改。
  • useshellHelper函数(mongo shell中的类型shellHelper.use)。它将变量db重新分配给新返回的数据库对象。

dbuc工作的解决方案之一是将以下代码添加到.mongorc.js

//The first time mongo shell loads, assign the value of dbuc. 
dbuc = db.getName().toUpperCase();

shellHelper.use = function (dbname) {
    var s = "" + dbname;
        if (s == "") {
           print("bad use parameter");
           return;
         }
 db = db.getMongo().getDB(dbname);

 //After new assignment extract and assign upper case of newly assgined db name to dbuc.
 dbuc = db.getName().toUpperCase();

 print("switched to db " + db.getName());

 }