MongoDB教程
MongoDB运算符
MongoDB命令
MongoDB数据库
MongoDB Shell
MongoDB云和工具

MongoDB 用户管理

MongoDB用户管理方法用于管理数据库的用户。

#1、 db.auth()

auth方法允许外壳程序内的用户向数据库提供身份验证。它可以接受用户名和密码,即db.auth( ,passwordPrompt())或db.auth( )。
我们可以定义一个用户集合,其中包含用户名,密码,机制和摘要密码标志。
db.auth( {
   user: <name>,
   pwd: "<cleartext password>",
   mechanism: <auth. mechanism>,
   digestPassword: <boolean>
} )
示例:
连接mongo shell之后,如果要进行身份验证,则必须在用户的身份验证数据库中发出db.auth():
use test
db.auth( "lidihuo", passwordPrompt() )

MongoDB用户管理方法

#2、 db.changeUserPassword(username,password)

更新用户密码。在定义用户的数据库(即您创建用户的数据库)中运行该方法。
示例
以下操作更改了密码。在产品数据库中将名为userUser的用户命名为SOh3TbYhx8ypJPxmt1oOfL:
use products
db.changeUserPassword("accountUser", passwordPrompt())
您还可以将新密码直接传递给db.changeUserPassword():
use products
db.changeUserPassword("accountUser", "SOh3TbYhx8ypJPxmt1oOfL")
输出:
MongoDB用户管理方法

#3、db.createUser()

此方法创建一个新用户,该用户在当前运行该方法的当前数据库的参数中指定。如果用户已经存在于指定的数据库中,则该方法返回重复错误。
使用createUser方法定义数据库用户的语法:
{
  user: "<name>",
  pwd: "<cleartext password>",
  customData: { <any info.> },
  roles: [
    { role: "<role>", db: "<database>" } | "<role>",
    ...
  ],
  authenticationRestrictions: [
     {
       clientSource: ["<IP>" | "<CIDR range>", ...],
       serverAddress: ["<IP>" | "<CIDR range>", ...]
     } ]
  mechanisms: [ "<SCRAM-SHA-1|SCRAM-SHA-256>", ... ],
  passwordDigestor: "<server|client>"
}
示例:
以下示例将在学生数据库上创建accountJTP用户。
use EmployeeAdmin
db.createUser( { user: "accountJTP",
           pwd: "<cleartext password>",
           customData: { Employee: 12345 },
            roles: [ { role: "clusterAdmin", db: "admin" },
                 { role: "readAnyDatabase", db: "admin" },
                   "readWrite"] },
           w: "majority" , wtimeout: 5000 } )
输出:
MongoDB用户管理方法

#4、 db.dropUser()

在删除具有userAdmin AnyDatabase角色的用户之前,db.dropUser()方法包装dropUser命令并从当前数据库中删除该用户。您必须明确表示,您至少还有一个具有用户管理特权的用户。
示例:
以下操作将jtpAdmin用户置于使用db.dropUser()创建studnet数据库。
use testwriter
db.dropUser("testwriter", {w: "majority", wtimeout: 4000})

MongoDB用户管理方法

#5、 db.removeUser()

没有其他使用此方法的方法。您可以使用此方法从当前数据库中删除指定的用户名。

#6、 db.updateUser()

updateUser方法用于更新指定数据库的用户配置文件。使用此方法将完全替换旧字段的值。此方法将更新添加到用户的角色数组。
语法:
db.updateUser(
   "<username>",
   {
     customData : { <any info.> },
     roles : [
       { role: "<role>", db: "<database>" } | "<role>",
       ...
     ],
     pwd: "<cleartext password>",
     authenticationRestrictions: [
        {
          clientSource: ["<IP>" | "<CIDR range>", ...],
          serverAddress: ["<IP>", | "<CIDR range>", ...]
        },
        ...
     ],
     mechanisms: [ "<SCRAM-SHA-1|SCRAM-SHA-256>", ... ],
     passwordDigestor: "<server|client>"
   },
   writeConcern: { <write concern> }
)
示例:
以下示例将使用db.updateUser()方法完全替换用户的customData和角色数据:
use Employee
db.updateUser( "NewMartin",
{
   customData : { employeeId : "001" },
   roles : [
      { role : "read", db : "assets"  }
   ]
} )
输出:
MongoDB用户管理方法
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4