Database Manual / Reference / Database Commands / User Management

createUser (database command)

Definition定义

createUser

Creates a new user on the database where you run the command. The createUser command returns a duplicate user error if the user exists.在运行命令的数据库上创建新用户。如果用户存在,createUser命令将返回重复用户错误。

Tip

In mongosh, this command can also be run through the db.createUser() helper method.mongosh中,此命令也可以通过db.createUser()辅助方法运行。

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.助手方法对mongosh用户来说很方便,但它们可能不会返回与数据库命令相同级别的信息。如果不需要便利性或需要额外的返回字段,请使用database命令。

Compatibility兼容性

This command is available in deployments hosted in the following environments:此命令在以下环境中托管的部署中可用:

  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Important

This command is not supported in MongoDB Atlas clusters. For information on Atlas support for all commands, see Unsupported Commands.MongoDB Atlas集群不支持此命令。有关Atlas支持所有命令的信息,请参阅不支持的命令

Syntax语法

The command has the following syntax:该命令具有以下语法:

Tip

You can use the passwordPrompt() method in conjunction with various user authentication management methods and commands to prompt for the password instead of specifying the password directly in the method or command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.您可以将passwordPrompt()方法与各种用户身份验证管理方法和命令结合使用,以提示输入密码,而不是直接在方法或命令调用中指定密码。但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

db.runCommand(
{
createUser: "<name>",
pwd: passwordPrompt(), // Or "<cleartext password>"
customData: { <any information> },
roles: [
{ role: "<role>", db: "<database>" } | "<role>",
...
],
writeConcern: { <write concern> },
authenticationRestrictions: [
{ clientSource: [ "<IP|CIDR range>", ... ], serverAddress: [ "<IP|CIDR range>", ... ] },
...
],
mechanisms: [ "<scram-mechanism>", ... ],
digestPassword: <boolean>,
comment: <any>
}
)

Command Fields命令字段

createUser has the following fields:具有以下字段:

Field字段Type类型Description描述
createUserstring字符串The name of the new user.新用户的名称。
pwdstring字符串

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

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

  • The user's password in cleartext string明文字符串形式的用户密码
  • passwordPrompt(), to prompt for the user's password,提示输入用户密码

You can use the passwordPrompt() method in conjunction with various user authentication management methods and commands to prompt for the password instead of specifying the password directly in the method or command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.您可以将passwordPrompt()方法与各种用户身份验证管理方法和命令结合使用,以提示输入密码,而不是直接在方法或命令调用中指定密码。但是,您仍然可以像使用早期版本的mongo shell一样直接指定密码。

customDatadocument文档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。
rolesarray数组The roles granted to the user. Can specify an empty array [] to create users without roles.授予用户的角色。可以指定一个空数组[]来创建没有角色的用户。
digestPasswordboolean布尔值

Optional. 可选。Indicates whether the server or the client digests the password.指示是服务器还是客户端对密码进行摘要。

If true, the server receives undigested password from the client and digests the password.如果为真,服务器将从客户端接收未消化的密码并对密码进行摘要。

If false, the client digests the password and passes the digested password to the server. Not compatible with SCRAM-SHA-256如果为false,客户端将解析密码并将解析后的密码传递给服务器。与SCRAM-SHA-256不兼容

The default value is true.默认值为true

writeConcerndocument文档Optional. 可选。The level of write concern for the operation. See Write Concern Specification.操作的写入关注级别。请参阅写入关注规范
authenticationRestrictionsarray数组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范围的列表。
mechanismsarray数组

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.指定创建SCRAM用户凭据的特定SCRAM机制。如果指定了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.需要将功能兼容性版本设置为4.0
  • Requires digestPassword to be true.要求digestPassword为true

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.

digestPasswordboolean布尔值

Optional. 可选。Indicates whether the server or the client digests the password.

If true, the server receives undigested password from the client and digests the password.

If false, the client digests the password and passes the digested password to the server. Not compatible with SCRAM-SHA-256

The default value is true.

commentany任意

Optional. 可选。A user-provided comment to attach to this command. Once set, this comment appears alongside records of this command in the following locations:

A comment can be any valid BSON type (string, integer, object, array, etc).注释可以是任何有效的BSON类型(字符串、整数、对象、数组等)。

Roles

In the roles field, you can specify both built-in roles and user-defined roles.

To specify a role that exists in the same database where createUser runs, you can either specify the role with the name of the role:

"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

The authenticationRestrictions document can contain only the following fields. The server throws an error if the authenticationRestrictions document contains an unrecognized field:

Field NameValueDescription描述
clientSourceArray of IP addresses and/or CIDR rangesIf 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. If the client's IP address is not present, the server does not authenticate the user.
serverAddressArray of IP addresses and/or CIDR rangesA list of IP addresses or CIDR ranges to which the client can connect. If present, the server will verify that the client's connection was accepted via an IP address in the given list. If the connection was accepted via an unrecognized IP address, the server does not authenticate the user.

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.

For more information on authentication in MongoDB, see Authentication on Self-Managed Deployments.

Behavior行为

User ID

MongoDB automatically assigns a unique userId to the user upon creation.

Encryption

Warning

By default, createUser sends all specified data to the MongoDB instance in cleartext, even if using passwordPrompt(). Use TLS transport encryption to protect communications between clients and the server, including the password sent by createUser. For instructions on enabling TLS transport encryption, see Configure mongod and mongos for TLS/SSL on Self-Managed Deployments.

MongoDB does not store the password in cleartext. The password is only vulnerable in transit between the client and the server, and only if TLS transport encryption is not enabled.

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.

To use Client Sessions and Causal Consistency Guarantees with $external authentication users (Kerberos, LDAP, or X.509 users), usernames cannot be greater than 10k bytes.

local Database

You cannot create users on the local database.

Username Limits

Usernames must consist of at least one character and cannot be larger than 7MB.

Required Access所需访问权限

The userAdmin and userAdminAnyDatabase built-in roles provide createUser and grantRole actions on their respective resources.

Example示例

The following createUser command creates a user accountAdmin01 on the products database. The command gives accountAdmin01 the clusterAdmin and readAnyDatabase roles on the admin database and the readWrite role on the products database:

Tip

You can use the passwordPrompt() method in conjunction with various user authentication management methods and commands to prompt for the password instead of specifying the password directly in the method or command call. However, you can still specify the password directly as you would with earlier versions of the mongo shell.

 db.getSiblingDB("products").runCommand( {
createUser: "accountAdmin01",
pwd: passwordPrompt(),
customData: { employeeId: 12345 },
roles: [
{ role: "clusterAdmin", db: "admin" },
{ role: "readAnyDatabase", db: "admin" },
"readWrite"
],
writeConcern: { w: "majority" , wtimeout: 5000 }
} )