MongoDB Show Current User

How do I show the current user that I'm logged into the mongo shell as? This is useful to know because it is possible to change the user that you are logged in as—e.g. db.auth("newuser", "password")—while in the interactive shell. One can easily lose track.

Update

Using the accepted answer as a base, I changed the prompt to include user, connection, and db:

Edit .mongorc.js in your home directory.

function prompt() {
var username = "anon";
var user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0];
var host = db.getMongo().toString().split(" ")[2];
var current_db = db.getName();


if (!!user) {
username = user.user;
}


return username + "@" + host + ":" + current_db + "> ";
}

Result:

MongoDB shell version: 2.4.8
connecting to: test


anon@127.0.0.1:test> use admin
switched to db admin


anon@127.0.0.1:admin> db.auth("a_user", "a_password")
1


a_user@127.0.0.1:admin>
66288 次浏览

The connectionStatus command shows authenticated users (if any, among some other data):

db.runCommand({connectionStatus : 1})

Which results in something like bellow:

{
"authInfo" : {
"authenticatedUsers" : [
{
"user" : "aa",
"userSource" : "test"
}
]
},
"ok" : 1
}

So if you are connecting from the shell, this is basically the current user

You can also add the user name to prompt by overriding the prompt function in .mongorc.js file, under OS user home directory. Roughly:

prompt = function() {
user = db.runCommand({connectionStatus : 1}).authInfo.authenticatedUsers[0]
if (user) {
return "user: " + user.user + ">"
}
return ">"
}

An example:

$ mongo -u "cc" -p "dd"
MongoDB shell version: 2.4.8
connecting to: test
user: cc>db.auth("aa", "bb")
1
user: aa>