MongoDB 显示当前用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21414608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:34:46  来源:igfitidea点击:

MongoDB Show Current User

mongodb

提问by James

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.

如何向当前用户显示我登录到 mongo shell 的身份?了解这一点很有用,因为可以更改您登录的用户——例如db.auth("newuser", "password")——在交互式 shell 中。一个人很容易迷失方向。

Update

更新

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

使用接受的答案作为基础,我将提示更改为包含用户、连接和数据库:

Edit .mongorc.jsin your home directory.

.mongorc.js在您的主目录中编辑。

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>

回答by Ori Dar

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

connectionStatus命令显示经过身份验证的用户(如果有的话,还有一些其他数据):

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

所以如果你从 shell 连接,这基本上是当前用户

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

您还可以通过覆盖OS 用户主目录下文件中的prompt函数来添加用户名以进行提示.mongorc.js。大致:

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>