Create Users in MongoDB on Ubuntu 22.04
Prerequisites
- MongoDB installed on your system
- MongoDB service running
- Access to the MongoDB shell (
mongosh
ormongo
)
Step 1: Connect to the MongoDB Shell
First, connect to your MongoDB shell by running:
mongosh
Or, if using the older shell version:
mongo
This will open the MongoDB shell where you can run commands.
Step 2: Switch to the Admin Database
To manage users, you need to switch to the admin
database:
use admin
Step 3: Create a Super (Root) User
To create a user with full administrative privileges (root), use the following command:
db.createUser({
user: "admin_user",
pwd: "strong_password_here",
roles: [ { role: "root", db: "admin" } ]
})
Replace admin_user
with the desired username and strong_password_here
with a strong password. This user will have full control over the entire MongoDB instance.
Step 4: Create a Normal User
Next, create a normal user with read and write permissions on a specific database. First, switch to the database where this user will operate:
use my_database
Then, create the user with the following command:
db.createUser({
user: "normal_user",
pwd: "normal_password_here",
roles: [ { role: "readWrite", db: "my_database" } ]
})
Replace normal_user
with the desired username, normal_password_here
with the password, and my_database
with the name of the database where this user will have access.
Step 5: Enable Authentication (Optional, but Recommended)
If you want to enforce user authentication, you need to enable it in the MongoDB configuration. To do this:
-
Open the MongoDB configuration file, typically located at
/etc/mongod.conf
:sudo nano /etc/mongod.conf
-
Find the following line and ensure
security
is uncommented andauthorization
is set toenabled
:security: authorization: enabled
-
Save the file and restart MongoDB:
sudo systemctl restart mongod
Step 6: Log in with the New User
To log in as the newly created users, you can use the following commands:
-
For the root user:
mongosh -u "admin_user" -p "strong_password_here" --authenticationDatabase "admin"
-
For the normal user:
mongosh -u "normal_user" -p "normal_password_here" --authenticationDatabase "my_database"
Finished
You have now successfully created both a root user and a normal user in MongoDB. The root user has full privileges, while the normal user has restricted access to a specific database.