How to Create and Drop Users in MongoDB
MongoDB provides a user management system where you can create users with different roles and permissions for your databases. These roles help control the level of access to data and operations. Below is a step-by-step guide on how to create and drop users in MongoDB.
1. Connect to MongoDB
Before managing users, you need to authenticate to the MongoDB instance with a user who has sufficient privileges (e.g., an admin user).
Replace admin
with your admin username and provide the correct password.
2. Create a User in MongoDB
MongoDB allows you to create users for specific databases with various roles that determine their permissions.
A. Syntax to Create a User
user
: The username you are creating.pwd
: The password for the user.roles
: The roles assigned to the user (e.g.,readWrite
,dbAdmin
,read
,root
).
B. Create a User with Specific Roles
Example 1: Create a User with readWrite
Role
To create a user with readWrite
access to a database (for example, blogDB
), run:
readWrite
: This role allows the user to read and write data in theblogDB
database.
Example 2: Create a User with Admin Role
To create an admin user with full control over a specific database:
dbAdmin
: This role grants the user administrative privileges over theblogDB
database, allowing tasks like creating indexes or managing collections.
Example 3: Create a User with read
Role
To create a user with read-only access to a database:
read
: This role grants the user read-only access to the database.
3. Drop (Delete) a User in MongoDB
You can also delete users that are no longer needed using the dropUser()
command.
A. Syntax to Drop a User
<username>
: The username of the user you want to delete.
B. Example of Dropping a User
To drop a user named appUser
from the blogDB
database:
This will permanently remove the appUser
from the blogDB
database.
4. List All Users in MongoDB
You can list all users in the current database by using the show users
command:
This will display a list of all users and their roles for the current database.
5. Modify (Update) a User in MongoDB
To modify an existing user's roles or permissions, you can use the updateUser()
method.
A. Syntax to Modify a User
B. Example of Modifying a User's Roles
If you want to add a readWrite
role to an existing user appUser
for the blogDB
database, run:
6. Example of Complete Workflow
1. Create an Admin User for the Admin Database
2. Create a User for Application Access
3. Drop a User
7. Summary
- Creating Users: You create users with specific roles using the
db.createUser()
method. You assign roles likereadWrite
,dbAdmin
, orroot
to grant appropriate permissions. - Dropping Users: To remove a user, use the
db.dropUser()
command. - Modifying Users: If you need to update a user's roles, use
db.updateUser()
. - Listing Users: Use the
show users
command to list all users in the current database.
Would you like more examples or further details on managing MongoDB users and roles? 🚀