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.
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 [email protected]:test> use admin switched to db admin [email protected]:admin> db.auth("a_user", "a_password") 1 [email protected]:admin>
For users created in MongoDB, MongoDB stores all user information, including name , password , and the user's authentication database , in the system. users collection in the admin database. Do not modify this collection directly.
If you want to check your databases list, use the command show dbs. Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. In MongoDB default database is test.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With