Make sure you have MongoDB installed and running on your system. Additionally, you should have a user with the necessary privileges to create roles.
Step 1: Connect to MongoDB:
Open your terminal or command prompt and connect to the MongoDB server using the mongo
shell:
1 | mongo |
Step 2: Switch to the Admin Database:
Roles are managed at the database level, so switch to the admin
database:
1 | use admin |
Step 3: Create a New Role:
Use the db.createRole()
method to define a new role. Roles in MongoDB consist of a name and privileges. Here’s an example of creating a custom role named “customRole” with read and write privileges on a specific database:
1 2 3 4 5 | db.createRole( { role: "customRole", privileges: [ { resource: { db: "yourDatabase", collection: "" }, actions: ["find", "insert", "update", "remove"] } ], roles: [] } ) |
Replace “customRole” with your desired role name, “yourDatabase” with the target database, and adjust the list of actions according to your needs.
Step 4: Verify Role Creation:
To ensure the role has been created successfully, you can use the following command:
1 | db.getRoles({ showBuiltinRoles: false }) |
This will display a list of all custom roles in the admin
database.
Step 5: Assign a Role to a User:
Now that you have created a role, you can assign it to a user. Connect to the target database and use the db.grantRolesToUser()
method:
use yourDatabase db.grantRolesToUser("yourUsername", ["customRole"])
Replace “yourDatabase” with the target database and “yourUsername” with the username you want to assign the role to.
Step 6: Verify Role Assignment:
Confirm that the role has been assigned to the user by using the following command:
1 | db.getUser("yourUsername") |
This will display the roles associated with the specified user.
Step 7: Exit the MongoDB Shell:
Exit the MongoDB shell by typing:
1 | exit |
Conclusion:
Creating roles in MongoDB allows you to define specific privileges for users, ensuring secure and controlled access to databases. By following these steps, you can create custom roles tailored to your application’s needs and assign them to users for effective access management. Proper use of roles enhances the security and integrity of your MongoDB database, providing a scalable and flexible solution for user access control.