Mongo 超级用户不会连接到 admin 以外的其他数据库

CES*_*SCO 3 mongodb

这是为什么?

$ mongo admin -u admin -p password --host 192.168.99.100
MongoDB shell version: 3.2.9
connecting to: 192.168.99.100:27017/admin
> show users
{
    "_id" : "admin.admin",
    "user" : "admin",
    "db" : "admin",
    "roles" : [
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        },
        {
            "role" : "dbAdminAnyDatabase",
            "db" : "admin"
        },
        {
            "role" : "readWriteAnyDatabase",
            "db" : "admin"
        }
    ]
}
> db^C
bye
cesco@laptop: ~/code/go/src/bitbucket.org/cescoferraro/cluster/containers on develop [!$]
$ mongo iot -u admin -p password --host 192.168.99.100
MongoDB shell version: 3.2.9
connecting to: 192.168.99.100:27017/iot
2016-09-25T22:22:36.829-0300 E QUERY    [thread1] Error: Authentication failed. :
DB.prototype._authOrThrow@src/mongo/shell/db.js:1441:20
@(auth):6:1
@(auth):1:2

exception: login failed
Run Code Online (Sandbox Code Playgroud)

Ste*_*nie 5

尽管admin您创建的用户通过 *AnyDatabase 角色具有全局权限,但用户凭据仅存在于admin数据库中。根据您的示例,如果您尝试访问的数据库中不存在匹配的用户凭据,您将无法进行身份验证。

mongo使用存储在与您尝试访问的数据库(adminvs iot)不同的数据库中的凭据对shell 进行身份验证,您可以:

1) 使用--authenticationDatabase以下用户凭据指定数据库:

 mongo iot --authenticationDatabase admin -u admin -p password --host 192.168.99.100
Run Code Online (Sandbox Code Playgroud)

2)指定默认数据库为/admin,然后更改为所需的目标数据库:

 $ mongo -u admin -p password 192.168.99.100/admin

 MongoDB shell version: 3.2.9
 connecting to: 192.168.99.100/admin

 > use iot
 switched to db iot
Run Code Online (Sandbox Code Playgroud)

第一个例子是最典型的方法。

注意:如果要按照第二个示例指定主机和数据库,则必须提供数据库连接字符串而不使用--host参数。