mongo-db
  1. mongo-db-role-management-methods

Role Management Methods - (MongoDB Shell)

MongoDB provides various methods to manage roles and their privileges. In this page, we will discuss the MongoDB shell commands that can be used to manage roles.

Syntax

Create a Role

db.createRole({role: "roleName", privileges: [ { resource : { db : "databaseName", collection : "collectionName"}, actions : ["action"] } ], roles: []})

Update a Role

db.updateRole("roleName", {privileges: [ { resource : { db : "databaseName", collection : "collectionName" }, actions : ["action"] } ]})

Drop a Role

db.dropRole("roleName")

Show All Roles

db.getRoles({showBuiltinRoles: true})

Example

Creating a role

db.createRole({ role: "userRole", privileges: [ { resource : { db : "test", collection : "users" }, actions : ["readWrite"] } ], roles: []})

Updating a role

db.updateRole("userRole", {privileges: [ { resource : { db : "test", collection : "accounts" }, actions : ["readWrite"] } ]})

Dropping a role

db.dropRole("userRole")

Listing all roles

db.getRoles({showBuiltinRoles: true})

Output

The above command will create/update/drop a role in the MongoDB shell. Once you execute the command successfully, it will return a confirmation message as output.

{ "ok" : 1 }

The getRoles command will show a list of roles present in the database. It will include both the user-defined and built-in roles.

Explanation

The createRole command creates a new role with the provided privileges and roles. The updateRole command modifies the existing role with the provided privileges. The dropRole command deletes the role and its privileges from the system. The getRoles command shows a list of all roles in the database, both user-defined and built-in.

Use

Role management methods in MongoDB Shell are used to control access to the database system resources. It enables us to provide fine-grained access control mechanisms to the users, ensuring the security of our database.

Important Points

  • createRole method creates a new role.
  • updateRole method modifies an existing role.
  • dropRole method deletes a role.
  • getRoles method shows a list of all roles.

Summary

In this page, we discussed the MongoDB shell commands that can be used to manage roles and their privileges. We covered the syntax, examples, output, explanation, use, important points, and concluded with the summary of the Role Management Methods in MongoDB Shell. By utilizing these commands, we can create, modify, and delete roles in MongoDB and grant permissions to perform specific actions on specific resources to authorized users.

Published on: