Users and roles in MongoDB can be managed through MongoDB’s built-in Role-Based Access Control (RBAC).
MongoDB user management involves creating users and assigning them roles that define their access to database resources and operations. MongoDB provides pre-defined roles that make it easier to assign user privileges. You can define additional roles that provide a finer granularity of control as well.
1. Create the user:
You can create users in MongoDB using the method `db.createUser()`. This method needs a document which includes a name, password, and roles for the user. \`\`\` db.createUser( { user: “user\_name”, pwd: “password”, roles: [ “role1”, “role2”, … ] } ) \`\`\`1. Update user:
Updating a user can be done by using the `db.updateUser()` method. For example, to change a user’s password: \`\`\` db.updateUser( “user\_name”, { pwd: “new\_password“ } ) \`\`\`1. Delete users:
Deleting a user can be done by using the `db.removeUser()` method. \`\`\` db.removeUser(“user\_name”) \`\`\`1. Manage roles:
MongoDB includes several built-in roles that administrators can use to control access to their databases. Some of the built-in roles include: read, readWrite, dbAdmin, userAdmin, clusterAdmin. If these pre-defined roles don’t meet your needs, you can also create and assign custom roles to users.To perform most of these user and role management commands, you must have the correct privileges – typically these commands are executed by a MongoDB user who has been assigned the `userAdmin` or `userAdminAnyDatabase` role.
These operations can also be performed by using MongoDB management tools with a graphical user interface, such as MongoDB Compass.