要在 MongoDB v3 中创建用户,请使用createUser()方法。这允许您创建用户,并且在创建时您还需要添加用户、密码和角色。这些角色分配权限。语法如下 -
use admin db.createUser( { user: “yourUserName", pwd: "yourPassword", roles: [ { role: "yourPermission", db: "yourDatabase" } ] } );
让我们实现上述语法以在 MongoDB v3 中创建用户 -
> use admin switched to db admin > db.createUser( ... { ... user: "Robert", ... pwd: "robert", ... roles: [ { role: "readWrite", db: "sample" } ] ... } ... );
上面,我们为新用户设置了以下内容 -
User: Robert Password: robert Roles: readWrite This will produce the following output: Successfully added user: { "user" : "Robert", "roles" : [ { "role" : "readWrite", "db" : "sample" } ] }
我们已经成功地在上面创建了一个新用户“Robert”。