📜  MongoDB用户管理方法

📅  最后修改于: 2020-11-23 01:26:47             🧑  作者: Mango

MongoDB用户管理方法

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

#1 db.auth()

auth方法允许外壳程序内的用户向数据库提供身份验证。它可以接受用户名和密码,即db.auth( ,passwordPrompt()或db.auth( )。

我们可以定义一个用户集合,其中包含用户名,密码,机制和摘要密码标志。

db.auth( {
   user: ,
   pwd: "",
   mechanism: ,
   digestPassword: 
} )

例:

连接mongo shell之后,如果要进行身份验证,则必须在用户的身份验证数据库中发出db.auth():

use test
db.auth( "javaTpoint", passwordPrompt() )

#2。 db.changeUserPassword(用户名,密码)

更新用户密码。在定义用户的数据库(即您创建用户的数据库)中运行该方法。

以下操作将产品数据库中名为accountUser的用户的密码更改为SOh3TbYhx8ypJPxmt1oOfL:

use products
db.changeUserPassword("accountUser", passwordPrompt())

您还可以将新密码直接传递给db.changeUserPassword():

use products
db.changeUserPassword("accountUser", "SOh3TbYhx8ypJPxmt1oOfL")

输出:

#3。 db.createUser( )

此方法创建一个新用户,该用户在该方法当前正在其上运行的当前数据库的参数中指定。如果用户已经存在于指定的数据库中,则该方法将返回重复错误。

使用createUser方法定义数据库用户的语法:

{
  user: "",
  pwd: "",
  customData: {  },
  roles: [
    { role: "", db: "" } | "",
    ...
  ],
  authenticationRestrictions: [
     {
       clientSource: ["" | "", ...],
       serverAddress: ["" | "", ...]
     } ]
  mechanisms: [ "", ... ],
  passwordDigestor: ""
}

例子:

以下示例将在学生数据库上创建accountJTP用户。

use EmployeeAdmin
db.createUser( { user: "accountJTP",
           pwd: "",
           customData: { Employee: 12345 },
            roles: [ { role: "clusterAdmin", db: "admin" },
                 { role: "readAnyDatabase", db: "admin" },
                   "readWrite"] },
           w: "majority" , wtimeout: 5000 } )

输出:

#4。 db.dropUser( )

db.dropUser()方法包装dropUser命令,并在删除具有userAdmin AnyDatabase角色的用户之前从当前数据库中删除该用户。必须明确说明,您至少还有一个具有用户管理特权的其他用户。

例:

以下操作使用db.dropUser()将jtpAdmin用户拖放到studnet数据库上。

use testwriter
db.dropUser("testwriter", {w: "majority", wtimeout: 4000})

#5。 db.removeUser( )

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

#6。 db.updateUser( )

updateUser方法用于更新指定数据库的用户配置文件。使用此方法将完全替换旧字段的值。此方法将更新添加到用户的角色数组。

句法:

db.updateUser(
   "",
   {
     customData : {  },
     roles : [
       { role: "", db: "" } | "",
       ...
     ],
     pwd: "",
     authenticationRestrictions: [
        {
          clientSource: ["" | "", ...],
          serverAddress: ["", | "", ...]
        },
        ...
     ],
     mechanisms: [ "", ... ],
     passwordDigestor: ""
   },
   writeConcern: {  }
)

例:

以下示例将使用db.updateUser()方法完全替换用户的customData和角色数据:

use Employee
db.updateUser( "NewMartin",
{
   customData : { employeeId : "001" },
   roles : [
      { role : "read", db : "assets"  }
   ]
} )

输出: