db.createUser()

On this page本页内容

Definition定义

db.createUser(user, writeConcern)

Creates a new user for the database on which the method is run. 为运行该方法的数据库创建新用户。db.createUser() returns a duplicate user error if the user already exists on the database.如果数据库中已存在用户,则返回重复的用户错误。

The db.createUser() method has the following syntax:db.createUser()方法语法如下所示:

Field字段Type类型Description描述
user document The document with authentication and access information about the user to create.包含要创建的用户的身份验证和访问信息的文档。
writeConcern document Optional.可选。The level of write concern for the creation operation. 创建操作的写入关注级别。The writeConcern document takes the same fields as the getLastError command.writeConcern文档采用与getLastError命令相同的字段。

The user document defines the user and has the following form:user文档定义了用户,并具有以下形式:

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

{
  user: "<name>",
  pwd: passwordPrompt(),      // Or  "<cleartext password>"
  customData: { <any information> },
  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>"
}

The user document has the following fields:user文档包含以下字段:

Field字段Type类型Description描述
user string The name of the new user.新用户的名称。
pwd string

The user’s password. 用户的密码。The pwd field is not required if you run db.createUser() on the $external database to create users who have credentials stored externally to MongoDB.如果在$external数据库上运行db.createUser(),以创建具有存储在MongoDB外部的凭据的用户,则不需要pwd字段。

The value can be either:该值可以是:

  • the user’s password in cleartext string, or明文字符串形式的用户密码,或
  • passwordPrompt() to prompt for the user’s password.以提示输入用户密码。

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

customData document Optional.可选。Any arbitrary information. 任何武断的信息。This field can be used to store any data an admin wishes to associate with this particular user. 此字段可用于存储管理员希望与此特定用户关联的任何数据。For example, this could be the user’s full name or employee id.例如,这可能是用户的全名或员工id。
roles array The roles granted to the user. 授予用户的角色。Can specify an empty array [] to create users without roles.可以指定空数组[]来创建没有角色的用户。
authenticationRestrictions array

Optional. 可选。The authentication restrictions the server enforces on the created user. 服务器对创建的用户实施的身份验证限制。Specifies a list of IP addresses and CIDR ranges from which the user is allowed to connect to the server or from which the server can accept users.指定允许用户连接到服务器或服务器可以接受用户的IP地址和CIDR范围的列表。

New in version 3.6.版本3.6中的新功能。

mechanisms array

Optional.可选。Specify the specific SCRAM mechanism or mechanisms for creating SCRAM user credentials. 指定用于创建紧急停堆用户凭据的特定紧急停堆机制。If authenticationMechanisms is specified, you can only specify a subset of the authenticationMechanisms.如果指定了authenticationMechanisms,则只能指定authenticationMechanisms的子集。

Valid values are:有效值为:

  • "SCRAM-SHA-1"
    • Uses the SHA-1 hashing function.使用SHA-1哈希函数。
  • "SCRAM-SHA-256"
    • Uses the SHA-256 hashing function.使用SHA-256哈希函数。
    • Requires featureCompatibilityVersion set to 4.0.需要将featureCompatibilityVersion设置为4.0
    • Requires passwordDigestor to be server.需要将passwordDigestory设置为server

The default for featureCompatibilityVersion is 4.0 is both SCRAM-SHA-1 and SCRAM-SHA-256.featureCompatibilityVersion的默认值为4.0,即SCRAM-SHA-1SCRAM-SHA-256

The default for featureCompatibilityVersion is 3.6 is SCRAM-SHA-1.featureCompatibilityVersion的默认值为3.6,即SCRAM-SHA-1

New in version 4.0.版本4.0中的新功能。

passwordDigestor string

Optional.可选。Indicates whether the server or the client digests the password.指示服务器或客户端是解析密码。

Available values are:可用值包括:

  • "server" (Default)
    The server receives undigested password from the client and digests the password.服务器从客户端接收未消化的密码,并消化密码。
  • "client" (Not compatible with SCRAM-SHA-256)
    The client digests the password and passes the digested password to the server.客户端解析密码并将解析后的密码传递给服务器。

Changed in version 4.0.在版本4.0中更改。The default value is "server". 默认值为"server"In earlier versions, the default value is "client".在早期版本中,默认值为"client"

Roles角色

In the roles field, you can specify both built-in roles and user-defined roles.roles字段中,可以指定内置角色用户定义角色

To specify a role that exists in the same database where db.createUser() runs, you can either specify the role with the name of the role:要指定运行db.createUser()的同一数据库中存在的角色,可以使用角色名称指定该角色:

"readWrite"

Or you can specify the role with a document, as in:也可以通过文档指定角色,如中所示:

{ role: "<role>", db: "<database>" }

To specify a role that exists in a different database, specify the role with a document.要指定存在于其他数据库中的角色,请使用文档指定该角色。

Authentication Restrictions身份验证限制

New in version 3.6.版本3.6中的新功能。

The authenticationRestrictions document can contain only the following fields. The server throws an error if the authenticationRestrictions document contains an unrecognized field:authenticationRestrictions文档只能包含以下字段。如果authenticationRestrictions文档包含无法识别的字段,服务器将抛出错误:

Field Name字段名ValueDescription描述
clientSource Array of IP addresses and/or CIDR rangesIP地址和/或CIDR范围数组 If present, when authenticating a user, the server verifies that the client’s IP address is either in the given list or belongs to a CIDR range in the list. 如果存在,在对用户进行身份验证时,服务器会验证客户端的IP地址是否在给定列表中,或者是否属于列表中的CIDR范围。If the client’s IP address is not present, the server does not authenticate the user.如果客户端的IP地址不存在,则服务器不会对用户进行身份验证。
serverAddress Array of IP addresses and/or CIDR rangesIP地址和/或CIDR范围数组 A list of IP addresses or CIDR ranges to which the client can connect. 客户端可以连接到的IP地址或CIDR范围的列表。If present, the server will verify that the client’s connection was accepted via an IP address in the given list. 如果存在,服务器将验证客户端的连接是否通过给定列表中的IP地址被接受。If the connection was accepted via an unrecognized IP address, the server does not authenticate the user.如果通过无法识别的IP地址接受连接,则服务器不会对用户进行身份验证。

Important

If a user inherits multiple roles with incompatible authentication restrictions, that user becomes unusable.如果用户继承了多个身份验证限制不兼容的角色,则该用户将无法使用。

For example, if a user inherits one role in which the clientSource field is ["198.51.100.0"] and another role in which the clientSource field is ["203.0.113.0"] the server is unable to authenticate the user.例如,如果用户继承了clientSource字段为["198.51.100.0"]的一个角色和clientSource字段为["203.0.113.0"]的另一个角色,则服务器无法对该用户进行身份验证。

For more information on authentication in MongoDB, see Authentication.有关MongoDB中身份验证的更多信息,请参阅身份验证

The db.createUser() method wraps the createUser command.db.createUser()方法包装createUser命令。

Behavior行为

User ID用户ID

Starting in version 4.0.9, MongoDB automatically assigns a unique userId to the user upon creation.从4.0.9版开始,MongoDB会在创建时自动为用户分配一个唯一的userId

Replica set复制集

If run on a replica set, db.createUser() is executed using majority write concern by default.如果在副本集上运行,db.createUser()将默认使用majority写入关注点执行。

Encryption加密

Warning

By default, db.createUser() sends all specified data to the MongoDB instance in cleartext, even if using passwordPrompt(). 默认情况下,db.createUser()将所有指定的数据以明文形式发送到MongoDB实例,即使使用passwordPrompt()Use TLS transport encryption to protect communications between clients and the server, including the password sent by db.createUser(). 使用TLS传输加密来保护客户端和服务器之间的通信,包括db.createUser()发送的密码。For instructions on enabling TLS transport encryption, see Configure mongod and mongos for TLS/SSL.有关启用TLS传输加密的说明,请参阅为TLS/SSL配置mongodmongos

MongoDB does not store the password in cleartext. MongoDB不以明文形式存储密码。The password is only vulnerable in transit between the client and the server, and only if TLS transport encryption is not enabled.只有在客户端和服务器之间传输时,并且只有在未启用TLS传输加密的情况下,密码才有漏洞。

External Credentials外部凭证

Users created on the $external database should have credentials stored externally to MongoDB, as, for example, with MongoDB Enterprise installations that use Kerberos.$external数据库上创建的用户应该具有存储在MongoDB外部的凭据,例如,使用Kerberos的MongoDB企业安装

Changed in version 3.6.3:在版本3.6.3中更改:To use sessions with $external authentication users (i.e. Kerberos, LDAP, x.509 users), the usernames cannot be greater than 10k bytes.要与$external authentication用户(即Kerberos、LDAP、x.509用户)使用会话,用户名不能超过10k字节。

local Database数据库

You cannot create users on the local database.无法在local数据库上创建用户。

Required Access所需访问权限

The userAdmin and userAdminAnyDatabase built-in roles provide createUser and grantRole actions on their respective resources.userAdminuserAdminAnyDatabase内置角色在各自的资源上提供createUsergrantRole操作。

Examples示例

The following db.createUser() operation creates the accountAdmin01 user on the products database.以下db.createUser()操作在products数据库上创建accountAdmin01用户。

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

use products
db.createUser( { user: "accountAdmin01",
                 pwd: passwordPrompt(),  // Or  "<cleartext password>"
                 customData: { employeeId: 12345 },
                 roles: [ { role: "clusterAdmin", db: "admin" },
                          { role: "readAnyDatabase", db: "admin" },
                          "readWrite"] },
               { w: "majority" , wtimeout: 5000 } )

The operation gives accountAdmin01 the following roles:该操作赋予accountAdmin01以下角色:

Create User with Roles创建具有角色的用户

The following operation creates accountUser in the products database and gives the user the readWrite and dbAdmin roles.以下操作在产品数据库中创建accountUser,并为用户提供readWritedbAdmin角色。

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

use products
db.createUser(
   {
     user: "accountUser",
     pwd: passwordPrompt(),  // Or  "<cleartext password>"
     roles: [ "readWrite", "dbAdmin" ]
   }
)

Create User without Roles创建没有角色的用户

The following operation creates a user named reportsUser in the admin database but does not yet assign roles:以下操作在admin数据库中创建名为reportsUser的用户,但尚未分配角色:

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

use admin
db.createUser(
   {
     user: "reportsUser",
     pwd: passwordPrompt(),  // Or  "<cleartext password>"
     roles: [ ]
   }
)

Create Administrative User with Roles创建具有角色的管理用户

The following operation creates a user named appAdmin in the admin database and gives the user readWrite access to the config database, which lets the user change certain settings for sharded clusters, such as to the balancer setting.下面的操作在admin数据库中创建一个名为appAdmin的用户,并为用户提供对配置数据库的读写访问权限,这允许用户更改分片集群的某些设置,例如平衡器设置。

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

use admin
db.createUser(
   {
     user: "appAdmin",
     pwd: passwordPrompt(),   // Or  "<cleartext password>"
     roles:
       [
         { role: "readWrite", db: "config" },
         "clusterAdmin"
       ]
   }
)

Create User with Authentication Restrictions创建具有身份验证限制的用户

The following operation creates a user named restricted in the admin database. 以下操作在admin数据库中创建名为restricted的用户。This user may only authenticate if connecting from IP address 192.0.2.0 to IP address 198.51.100.0.该用户只能在从IP地址192.0.2.0连接到IP地址198.51.100.0时进行身份验证。

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

use admin
db.createUser(
   {
     user: "restricted",
     pwd: passwordPrompt(),      // Or  "<cleartext password>"
     roles: [ { role: "readWrite", db: "reporting" } ],
     authenticationRestrictions: [ {
        clientSource: ["192.0.2.0"],
        serverAddress: ["198.51.100.0"]
     } ]
   }
)

Create User with SCRAM-SHA-256 Credentials Only仅使用SCRAM-SHA-256凭据创建用户

Note

To use SCRAM-SHA-256, the featureCompatibilityVersion must be set to 4.0. 要使用SCRAM-SHA-256featureCompatibilityVersion必须设置为4.0For more information on featureCompatibilityVersion, see View FeatureCompatibilityVersion and setFeatureCompatibilityVersion.有关featureCompatibilityVersion的更多信息,请参阅查看FeatureCompatibilityVersionsetFeatureCompatibilityVersion

The following operation creates a user with only SCRAM-SHA-256 credentials.以下操作将创建一个仅具有SCRAM-SHA-256凭据的用户。

Tip

Starting in version 4.2 of the mongo shell, you can use the passwordPrompt() 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. 从mongo shell的4.2版开始,您可以将passwordPrompt()方法与各种用户身份验证/管理方法/命令结合使用,以提示输入密码,而不是直接在方法/命令调用中指定密码。However, you can still specify the password directly as you would with earlier versions of the mongo shell.但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

use reporting
db.createUser(
   {
     user: "reportUser256",
     pwd: passwordPrompt(),   // Or  "<cleartext password>"
     roles: [ { role: "readWrite", db: "reporting" } ],
     mechanisms: [ "SCRAM-SHA-256" ]
   }
)

If the authenticationMechanisms parameter is set, the mechanisms field can only include values specified in the authenticationMechanisms parameter.如果设置了authenticationMechanisms参数,则mechanisms字段只能包括authenticationMechanisms参数中指定的值。