db.createUser()

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 theuser already exists on the database.

The db.createUser() method has the following syntax:

FieldTypeDescriptionuserdocumentThe document with authentication and access information about theuser to create.writeConcerndocumentOptional. The level of write concern for thecreation operation. The writeConcern document takes the samefields as the getLastError command.

The user document defines the user and has the following form:

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. {
  2. user: "<name>",
  3. pwd: passwordPrompt(), // Or "<cleartext password>"
  4. customData: { <any information> },
  5. roles: [
  6. { role: "<role>", db: "<database>" } | "<role>",
  7. ...
  8. ],
  9. authenticationRestrictions: [
  10. {
  11. clientSource: ["<IP>" | "<CIDR range>", ...],
  12. serverAddress: ["<IP>" | "<CIDR range>", ...]
  13. },
  14. ...
  15. ],
  16. mechanisms: [ "<SCRAM-SHA-1|SCRAM-SHA-256>", ... ],
  17. passwordDigestor: "<server|client>"
  18. }

The user document has the following fields:

FieldTypeDescriptionuserstringThe name of the new user.pwdstringThe user’s password. The pwd field is notrequired if you run db.createUser() on the $externaldatabase to create users who have credentials stored externally toMongoDB.

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 canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

customDatadocumentOptional. Any arbitrary information. This field can be used to store any dataan admin wishes to associate with this particular user. For example,this could be the user’s full name or employee id.rolesarrayThe roles granted to the user. Can specify an empty array [] tocreate users without roles.authenticationRestrictionsarrayOptional. The authentication restrictions the server enforces on the createduser. Specifies a list of IP addresses andCIDR ranges from which theuser is allowed to connect to the server or from which the server canaccept users.

New in version 3.6.

mechanismsarrayOptional. Specify the specific SCRAM mechanism or mechanisms for creatingSCRAM user credentials. If authenticationMechanisms isspecified, you can only specify a subset of theauthenticationMechanisms.

Valid values are:

  • "SCRAM-SHA-1"
    • Uses the SHA-1 hashing function.
  • "SCRAM-SHA-256"
    • Uses the SHA-256 hashing function.
    • Requires featureCompatibilityVersion set to 4.0.
    • Requires passwordDigestor to be server.The default for featureCompatibilityVersion is 4.0 is bothSCRAM-SHA-1 and SCRAM-SHA-256.

The default for featureCompatibilityVersion is 3.6 isSCRAM-SHA-1.

New in version 4.0.

passwordDigestorstringOptional. Indicates whether the server or the client digests the password.

Available values are:

    • "server" (Default)
    • The server receives undigested password from the client anddigests the password.
    • "client" (Not compatible with SCRAM-SHA-256)
    • The client digests the password and passes the digestedpassword to the server.

Changed in version 4.0: The default value is "server". In earlier versions, thedefault value is "client".

Roles

In the roles field, you can specify bothbuilt-in roles and user-definedroles.

To specify a role that exists in the same database wheredb.createUser() runs, you can either specify the role with the name ofthe role:

  1. "readWrite"

Or you can specify the role with a document, as in:

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

To specify a role that exists in a different database, specify the rolewith a document.

Authentication Restrictions

New in version 3.6.

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

Field NameValueDescription
clientSourceArray of IP addresses and/orCIDR rangesIf present, when authenticating a user, the server verifiesthat the client’s IP address is either in the given list orbelongs to a CIDR range in the list. If the client’s IP addressis not present, the server does not authenticate the user.
serverAddressArray of IP addresses and/orCIDR rangesA list of IP addresses or CIDR ranges to which the client canconnect. If present, the server will verify that the client’sconnection was accepted via an IP address in the given list. Ifthe connection was accepted via an unrecognized IP address, theserver does not authenticate the user.

Important

If a user inherits multiple roles with incompatible authenticationrestrictions, that user becomes unusable.

For example, if a user inherits one role in which theclientSource field is ["198.51.100.0"] and another role inwhich the clientSource field is ["203.0.113.0"] the server isunable to authenticate the user.

For more information on authentication in MongoDB, seeAuthentication.

The db.createUser() method wraps the createUsercommand.

Behavior

User Id

Starting in version 4.0.9, MongoDB automatically assigns a uniqueuserId to the user upon creation.

Replica set

If run on a replica set, db.createUser() is executed using majority write concern by default.

Encryption

Warning

By default, db.createUser() sends all specified data to the MongoDBinstance in cleartext, even if using passwordPrompt(). UseTLS transport encryption to protect communications between clientsand the server, including the password sent by db.createUser(). Forinstructions on enabling TLS transport encryption, seeConfigure mongod and mongos for TLS/SSL.

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

External Credentials

Users created on the $external database should have credentialsstored externally to MongoDB, as, for example, with MongoDBEnterprise installations that use Kerberos.

Changed in version 3.6.3: To use sessions with $external authentication users (i.e.Kerberos, LDAP, x.509 users), the usernames cannot be greaterthan 10k bytes.

local Database

You cannot create users on the local database.

Required Access

The userAdmin anduserAdminAnyDatabase built-in rolesprovide createUser andgrantRole actions on their respective resources.

Examples

The following db.createUser() operation creates theaccountAdmin01 user on the products database.

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

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

The operation gives accountAdmin01 the following roles:

  • the clusterAdmin and readAnyDatabase roles on the admindatabase
  • the readWrite role on the products database

Create User with Roles

The following operation creates accountUser in the products databaseand gives the user the readWrite and dbAdmin roles.

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. use products
  2. db.createUser(
  3. {
  4. user: "accountUser",
  5. pwd: passwordPrompt(), // Or "<cleartext password>"
  6. roles: [ "readWrite", "dbAdmin" ]
  7. }
  8. )

Create User without Roles

The following operation creates a user named reportsUser in the admindatabase but does not yet assign roles:

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. use admin
  2. db.createUser(
  3. {
  4. user: "reportsUser",
  5. pwd: passwordPrompt(), // Or "<cleartext password>"
  6. roles: [ ]
  7. }
  8. )

Create Administrative User with Roles

The following operation creates a user named appAdmin in theadmin database and gives the user readWrite access to theconfig database, which lets the user change certain settings forsharded clusters, such as to the balancer setting.

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. use admin
  2. db.createUser(
  3. {
  4. user: "appAdmin",
  5. pwd: passwordPrompt(), // Or "<cleartext password>"
  6. roles:
  7. [
  8. { role: "readWrite", db: "config" },
  9. "clusterAdmin"
  10. ]
  11. }
  12. )

Create User with Authentication Restrictions

The following operation creates a user named restricted in theadmin database. This user may only authenticate if connecting fromIP address 192.0.2.0 to IP address 198.51.100.0.

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. use admin
  2. db.createUser(
  3. {
  4. user: "restricted",
  5. pwd: passwordPrompt(), // Or "<cleartext password>"
  6. roles: [ { role: "readWrite", db: "reporting" } ],
  7. authenticationRestrictions: [ {
  8. clientSource: ["192.0.2.0"],
  9. serverAddress: ["198.51.100.0"]
  10. } ]
  11. }
  12. )

Create User with SCRAM-SHA-256 Credentials Only

Note

To use SCRAM-SHA-256, thefeatureCompatibilityVersion must be set to 4.0. For moreinformation on featureCompatibilityVersion, see View FeatureCompatibilityVersion andsetFeatureCompatibilityVersion.

The following operation creates a user with only SCRAM-SHA-256credentials.

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. use reporting
  2. db.createUser(
  3. {
  4. user: "reportUser256",
  5. pwd: passwordPrompt(), // Or "<cleartext password>"
  6. roles: [ { role: "readWrite", db: "reporting" } ],
  7. mechanisms: [ "SCRAM-SHA-256" ]
  8. }
  9. )

If the authenticationMechanisms parameter is set, themechanisms field can only include values specified in theauthenticationMechanisms parameter.