This guide provides step-by-step instructions to deauthorize and set up new users in MongoDB using mongosh.
- Access to MongoDB: Ensure you can connect to your MongoDB server via
mongosh. - Admin Access: You need a user with the
userAdminrole in theadmindatabase.
Run the following command to connect to your MongoDB server:
mongosh --host <your_server_ip> --port <port> -u <admin_user> -p <password> --authenticationDatabase adminReplace the placeholders:
<your_server_ip>: MongoDB server's IP address<port>: Port number (default is27017)<admin_user>: Admin username<password>: Admin password
If the user is associated with a specific database, switch to that database:
use <database_name>Replace <database_name> with the name of the database.
Remove the user with:
db.dropUser("<username>")Replace <username> with the name of the user to be removed.
To confirm the user has been removed, list all users:
db.getUsers()Switch to the database where the user will be created:
use <database_name>Replace <database_name> with the target database.
Run the following command:
db.createUser({
user: "<username>",
pwd: "<password>",
roles: [
{ role: "<role>", db: "<database_name>" }
]
})Replace:
<username>: New user's name.<password>: New user's password.<role>: Desired role (e.g.,readWrite,read).<database_name>: Database where the role applies.
Example: To create a user with readWrite access to the mydb database:
db.createUser({
user: "newUser",
pwd: "securePassword123",
roles: [
{ role: "readWrite", db: "mydb" }
]
})To confirm the user was created successfully:
db.getUsers()Log out and log back in as the new user to test their credentials:
mongosh --host <your_server_ip> --port <port> -u newUser -p securePassword123 --authenticationDatabase mydb| Role | Description |
|---|---|
read |
Grants read-only access to a specific database. |
readWrite |
Grants read and write access to a specific database. |
dbAdmin |
Grants administrative tasks on a specific database. |
userAdmin |
Grants ability to manage users on a specific database. |
clusterAdmin |
Grants administrative tasks on the entire cluster. |
To see all users across all databases (as admin):
use admin
db.system.users.find().pretty()This command lists all users, their roles, and their associated databases.
This document provides a complete overview of user management using mongosh. Let us know if further clarification is needed!
And voila! https://gist.github.com/ideabrian/5b1e1bf81197475ef2dbcfe24e73e248