db.updateUser()

Definition

  • db.updateUser(username, update, writeConcern)
  • Updates the user’s profile on the database on which you run the method.An update to a field completely replaces the previous field’s values.This includes updates to the user’s roles array.

Warning

When you update the roles array, you completely replace theprevious array’s values. To add or remove roles without replacing allthe user’s existing roles, use the db.grantRolesToUser() ordb.revokeRolesFromUser() methods.

The db.updateUser() method uses the following syntax:

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

The db.updateUser() method has the following arguments.

ParameterTypeDescriptionusernamestringThe name of the user to update.updatedocumentA document containing the replacement data for the user. Thisdata completely replaces the corresponding data for the user.writeConcerndocumentOptional. The level of write concern for theupdate operation. The writeConcern document takes the samefields as the getLastError command.

The update document specifies the fields to update and theirnew values. All fields in the update document are optional,but must include at least one field.

The update document has the following fields:

FieldTypeDescriptioncustomDatadocumentOptional. Any arbitrary information.rolesarrayOptional. The roles granted to the user. An update to the roles arrayoverrides the previous array’s values.pwdstringOptional. The user’s password. 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.

authenticationRestrictionsarrayOptional. The authentication restrictions the server enforces upon the user.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. The specific SCRAM mechanism or mechanisms for the user credentials.If authenticationMechanisms is specified, you can onlyspecify a subset of the authenticationMechanisms.

If updating the mechanisms field without the password, you can onlyspecify a subset of the user’s current mechanisms, and only theexisting user credentials for the specified mechanism or mechanismsare retained.

If updating the password along with the mechanisms, new set ofcredentials are stored for the user.

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.

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.updateUser() 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.updateUser() method wraps the updateUsercommand.

Behavior

Replica set

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

Encyption

Warning

By default, db.updateUser() 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.updateUser(). 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.

Required Access

You must have access that includes the revokeRoleaction on all databases in order to update auser’s roles array.

You must have the grantRoleaction on a role’s database to add a role to a user.

To change another user’s pwd or customData field, you must havethe changeAnyPassword and changeAnyCustomDataactions respectively on that user’s database.

To modify your own password and custom data, you must have privilegesthat grant changeOwnPassword andchangeOwnCustomDataactions respectively on the user’s database.

Example

Given a user appClient01 in the products database with the followinguser info:

  1. {
  2. _id : "products.appClient01",
  3. userId : UUID("c5d88855-3f1e-46cb-9c8b-269bef957986"), // Starting in MongoDB 4.0.9
  4. user : "appClient01",
  5. db : "products",
  6. customData : { empID : "12345", badge : "9156" },
  7. roles : [
  8. {
  9. role : "readWrite",
  10. db : "products"
  11. },
  12. {
  13. role : "read",
  14. db : "inventory"
  15. }
  16. ],
  17. mechanisms : [ // Starting in MongoDB 4.0
  18. "SCRAM-SHA-1",
  19. "SCRAM-SHA-256"
  20. ],
  21. authenticationRestrictions : [ {
  22. clientSource: ["69.89.31.226"],
  23. serverAddress: ["172.16.254.1"]
  24. } ]
  25. }

The following db.updateUser() method completely replaces theuser’s customData and roles data:

  1. use products
  2. db.updateUser( "appClient01",
  3. {
  4. customData : { employeeId : "0x3039" },
  5. roles : [
  6. { role : "read", db : "assets" }
  7. ]
  8. } )

The user appClient01 in the products database now has the followinguser information:

  1. {
  2. _id : "products.appClient01",
  3. userId : UUID("c5d88855-3f1e-46cb-9c8b-269bef957986"), // Starting in MongoDB 4.0.9
  4. user : "appClient01",
  5. db : "products",
  6. customData : { employeeId : "0x3039" },
  7. roles : [
  8. {
  9. role : "read",
  10. db : "assets"
  11. }
  12. ],
  13. mechanisms : [ // Starting in MongoDB 4.0
  14. "SCRAM-SHA-1",
  15. "SCRAM-SHA-256"
  16. ],
  17. authenticationRestrictions : [ {
  18. clientSource: ["69.89.31.226"],
  19. serverAddress: ["172.16.254.1"]
  20. } ]
  21. }

Update User to Use 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 updates a user who currently have bothSCRAM-SHA-256 and SCRAM-SHA-1 credentials to have onlySCRAM-SHA-256 credentials.

Note

  • If the password is not specified along with the mechanisms,you can only update the mechanisms to a subset of the currentSCRAM mechanisms for the user.
  • If the password is specified along with the mechanisms, youcan specify any supported SCRAM mechanism or mechanisms.
  • For SCRAM-SHA-256, the passwordDigestor must be thedefault value "server".
  1. use reporting
  2. db.updateUser(
  3. "reportUser256",
  4. {
  5. mechanisms: [ "SCRAM-SHA-256" ]
  6. }
  7. )