MongoDB 默认没有设置用户名密码,须要咱们本身设置。简单来讲首先设置一个管理全部用户角色的用户admin,而后根据须要为此用户添加其余角色便可。mongodb
1.设置一个管理全部用户角色的用户adminshell
例如,如下内容使用角色和 角色myUserAdmin
在admin
数据库中 建立用户。数据库
use admin db.createUser( { user: "myUserAdmin", pwd: passwordPrompt(), // or cleartext password roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] } )
注意上面代码中的passwordPrompt():spa
Starting in version 4.2 of the
mongo
shell, you can use thepasswordPrompt()
method in conjunction with various user authentication/management methods/commands to prompt for the password instead of specifying the password directly in the method/command call. However, you can still specify the password directly as you would with earlier versions of themongo
shell.code从
mongo
shell的4.2版开始,您能够将该passwordPrompt()
方法与各类用户身份验证/管理方法/命令结合使用来提示输入密码,而不是直接在方法/命令调用中指定密码。可是,您仍然能够像使用早期版本的mongo
shell 同样直接指定密码 。blog
而后须要受权(笔者在执行上面操做以后没有重启直接进行下一步能够实现):ci
use admin //若是不重启能够,能够不用输入这句
db.auth("myUserAdmin", "abc123" )
返回1表示成功。get
2.建立数据库用户it
use test db.createUser( { user: "myTester", pwd: passwordPrompt(), // or cleartext password roles: [ { role: "readWrite", db: "test" }, { role: "read", db: "reporting" } ] } )