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

MongoDB: Custom command defined in .mongorc.js

我想定义一个自定义 Mongo shell 命令。鉴于 .mongorc.js 如下所示:

var dbuc;

(function () {
    dbuc = (function () {
        return db.getName().toUpperCase();
    })();
})();

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

> db
test
> dbuc
TEST

> use otherbase

> db
otherbase
> dbuc
TEST

我看到 .mongorc.jsmongo 运行 之前是 运行,这就是为什么 dbuc 变量已分配初始数据库的值 - 测试。但我很想知道如何获取当前数据库的名称,无论我打开了什么基础。

有几点需要注意:

  • 在mongo shell中,typeof db是一个javascript对象,typeof dbuc是字符串。
  • 我相信,在您的代码中,dbuc 值被分配一次并且在调用 use 时不会改变。
  • use 是一个 shellHelper 函数(在 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());
};