db.grantPrivilegesToRole() in mongoDB

grantPrivilegesToRole(rolename, privileges, writeConcern?)

This method grants additional privileges to a user-defined role.


Syntax:

db.grantPrivilegesToRole(rolename, privileges, writeConcern?) 


Example 1: When the role is user-defined and present.

MongoDB

db.grantPrivilegesToRole(

  "myAdmin",

  [

    {

      resource: { db: "admin", collection: "" },

      actions: [ "insert" ]

    },

    {

      resource: { db: "admin", collection: "system.js" },

      actions: [ "find" ]

    }

  ]

)



Example 2: When the role is user build-in.

MongoDB

db.grantPrivilegesToRole(

    "dbAdmin",
 
    [
 
      {
 
        resource: { db: "admin", collection: "" },
 
        actions: [ "insert" ]
 
      },
 
      {
 
        resource: { db: "admin", collection: "system.js" },
 
        actions: [ "find" ]
 
      }
 
    ]
 
  )


Output:

uncaught exception: Error: dbAdmin@admin is a built-in role and cannot be modified :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.grantPrivilegesToRole@src/mongo/shell/db.js:1731:15
@(shell):1:1


Example 3: When the role is not present.

MongoDB

db.grantPrivilegesToRole(

    "newRole",
 
    [
 
      {
 
        resource: { db: "admin", collection: "" },
 
        actions: [ "insert" ]
 
      },
 
      {
 
        resource: { db: "admin", collection: "system.js" },
 
        actions: [ "find" ]
 
      }
 
    ]
 
  )


Output:

uncaught exception: Error: Role newRole@admin not found :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.grantPrivilegesToRole@src/mongo/shell/db.js:1731:15
@(shell):1:1


No comments:

Post a Comment