Sunday 10 August 2014

Global Variable in MongoDB using .mongorc.js

Today we will see something interesting. Every time we login to our mongod process using the mongo client, it gives us a blank prompt like below:

MongoDB shell version: 2.6.3
connecting to: test
>

This might sound little boring. To change the same we can make use of the prompt function variable of MongoDB. For example if you want to show your name as the prompt you can simply set up the prompt variable like below:

MongoDB shell version: 2.6.3
connecting to: test
> var prompt = function() { return "Tridib using MongoDB >" };

Once you hit enter you will see the below prompt.

Tridib using MongoDB >

This might be a temporary approach as the scope of the prompt variable set in this mongo shell is limited to this shell only. Next time when you login it will be reset to blank.

To avoid this you can set up this at a global level. Go to your home directory C:\Users\<USERNAME> for windows or $HOME for Unix/Linux. You will see a file called .mongorc.js. Open this file in an editor and add the following content (don't forget to save the file):

var host = db.serverStatus().host;
var prompt = function() { return db+"@"+host+"> "; }

This will prompt the current database you have logged in and the host name of your system. You can change the prompt function of your own choice as well.

test@SOMEHOST>

The file .mongorc.js file is used to set up global function or variables you want to set up, every time the mongo client loads.


<< Prev                                                                                     Next >>

No comments:

Post a Comment