Updated on 2022-09-21 GMT+08:00

Creating a User

Precautions

  • All the following operations require permissions. By default, user rwuser has the required permissions. If a user-defined user is used for management, check whether the user has the required permissions.
  • Connect to a DB instance as a user who has the required permission (for example, rwuser).
  • You can use createUser to create required users and configure roles to control user rights. Note that the passwordDigestor parameter must be set to server. Otherwise, the command fails to be executed. This restriction is added to prevent security risks.

Creating a User

db.createUser(user, writeConcern)

  • In the command, user is mandatory and the type is document. It contains the identity authentication and access information of the user to be created.
  • writeConcern is an optional parameter of the document type. It contains the write concern level of the creation operation.
The user document defines users. The format is as follows:
{
  user: "<name>",
  pwd: "<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>"
}
Table 1 Description of parameter user

Field

Type

Description

user

string

The new username.

pwd

string

User password. If you run db.createUser() on the $external database to create a user who stores credentials outside of MongoDB, the pwd field is not required.

customData

Document

Optional. Any information, which can be used to store any data that the administrator wants to associate with this particular user. For example, this could be the user's full name or employee ID.

roles

Array

The role assigned to the user. You can specify an empty array [] to create a user without a role.

authenticationRestrictions

Array

Optional. The authentication restrictions forcibly imposed by the server on the created user. It is used to specify the IP address or IP address segment that can be accessed by the role.

mechanisms

Array

Optional. The specific SCRAM mechanism or mechanisms for the user credentials. Valid values are SCRAM-SHA-1 and SCRAM-SHA-256.

passwordDigestor

string

Optional. Whether to verify the password on the server or client. The default value is server.