Differences between createUser and grantRolesToUser

I just watched Built-In Roles: Part 2 and what the instructor says confuses me.

He explains roles parameter in db.createUser and the db.grantRolesToUser method. I thought this to method are the same one is for assigning roles when creating user but one is for assigning roles to existing users. However, he says something that I think means that roles that I assign using db.createUser are used for authentication. So my first question is what is difference between roles parameter of db.createUser and db.grantRolesToUser.

My second question is that roles that we define in either db.createUser or db.grantRolesToUser are related to --authenticationDatabase parameter we use when connecting to a mongodb session?

Hi @Meysam_Naseri,

Both are used to grant roles to a user. One at the time of creation and one after the creation. For example there might be cases when an employee is promoted to a senior position in a company and that my get them access to new set of information / privileges and hence you can use the db.grantRolesToUser()method to grant them additional roles.

You create a user on any specific database and using that database you authenticate yourself. Now, when you assign roles to a user - you basically grant them privileges to perform sets of actions on defined resources.

The roles that you define in either of the method gives them privilege to the database that you have specified in the function. For example, I will run this command to switch to test database:

use test

after switching to test database, let’s create a user by running this command:

    user: "test-user",
    pwd: "user_password",
    roles: [
      { role: "dbAdmin", db: "employee"}
    ]
  })

Here user will authenticate using test database but user would be able to perform dbAdmin related task on the employee database.

Hope it helps!!

1 Like