w3resource

MongoDB: db.grantRolesToUser() method

db.grantRolesToUser()

The db.grantRolesToUser() method is used to grants an additional role and its privileges to a user.

Syntax:

db.grantRolesToUser( "<username>", [ <roles> ], { <writeConcern> } )

Parameters:

Name Description Required /
Optional
Type
user The name of the user to whom to grant roles. Required string
roles An array of additional roles to grant to the user. Required array
writeConcern The level of write concern for the modification. The writeConcern document takes the same fields as the getLastError command. Optional document

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

To specify a role that exists in the same database where db.grantRolesToUser() 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.

Example: MongoDB: db.grantRolesToUser() method

Given a user mynewuser in the test database with the following roles:

> db.getUser("mynewuser");
{
        "_id" : "test.mynewuser",
        "user" : "mynewuser",
        "db" : "test",
        "roles" : [
                {
                        "role" : "readWrite",
                        "db" : "test"
                },
                {
                        "role" : "dbAdmin",
                        "db" : "test"
                }
        ]
}

The following grantRolesToUser() operation gives mynewuser the read role on the orders database.


use test
db.grantRolesToUser(
   "mynewuser",
   [ "readWrite" , { role: "read", db: "orders" } ],
   { w: "majority" , wtimeout: 4000 }
);

The user mynewuser in the test database now has the following roles:

db.getUser("mynewuser");

      "_id" : "test.mynewuser",
      "user" : "mynewuser",
      "db" : "test",
      "roles" : [
              {
                      "role" : "read",
                      "db" : "orders"
              },
              {
                      "role" : "readWrite",
                      "db" : "test"
              },
              {
                      "role" : "dbAdmin",
                      "db" : "test"
              }
      ]

Retrieve the restaurants data from here

Required Access

You must have the grantRole action on a database to grant a role on that database.

Previous: db.dropUser() method
Next: db.revokeRolesFromUser() method



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/mongodb/shell-methods/user-management/db-grantRolesToUser.php