Search code examples
mongodbmongodb-shell

MongoDB: Custom command defined in .mongorc.js


I'd like to define a custom Mongo shell command. Given .mongorc.js is like below:

var dbuc;

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

I'm getting proper upper-cased name for initial database, yet when I switch to other database I'm still getting name of the initial database instead of current one.

> db
test
> dbuc
TEST

> use otherbase

> db
otherbase
> dbuc
TEST

I see .mongorc.js is run before mongo runs and that's why dbuc variable has assigned value of initial database - test. But I rather wonder how to get a name of current database whatever base I turned on.


Solution

  • There are a few things to note:

    • In mongo shell, typeof db is a javascript object and typeof dbuc is string.
    • I believe, in your code, dbuc value is assigned once and does not change when use is called.
    • use is a shellHelper function(type shellHelper.use in mongo shell). It reassigns variable db with newly returned database object.

    One of the solutions, for dbuc to work, is to add following code to .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());
    };