Adding new user to MongoDB
MongoDB, by default, listens on **port 27017**. To secure your MongoDB instance, you typically add user accounts to restrict access to the database.
Here’s how to add an administrative user account and configure MongoDB to use authentication.
### **Step 1: Access the MongoDB Shell**
First, access the MongoDB shell (`mongosh`) to interact with the MongoDB server.
1mongosh
If you're running MongoDB locally, this will connect to the MongoDB instance on `localhost:27017`.
### **Step 2: Switch to the Admin Database**
MongoDB uses a special `admin` database to store user credentials for administrators. Switch to the `admin` database:
1use admin
### **Step 3: Create an Admin User**
To create a new administrative user, run the following command. This user will have `root` privileges and will be able to manage databases and users.
1db.createUser({2 user: "admin_user",3 pwd: "your_secure_password",4 roles: [{ role: "root", db: "admin" }]5})
- **`user`**: The username for the new admin account (e.g., `"admin_user"`).
- **`pwd`**: The password for the user (e.g., `"your_secure_password"`).
- **`roles`**: Assigns the `"root"` role to the user. The `"root"` role provides full access to all databases.
### **Step 4: Enable Authentication in MongoDB Configuration**
By default, MongoDB allows connections without authentication. You need to enable authentication in MongoDB's configuration file.
#### **Edit MongoDB Configuration**
1. **Open the MongoDB configuration file** (`mongod.conf`), usually located in `/etc/mongod.conf`:
1sudo nano /etc/mongod.conf
2. **Enable Authentication**:
Look for the `security` section in the config file. If it's not present, add it:
1 security:2 authorization: "enabled"
**Save and Exit**: Press `Ctrl + X`, then `Y`, and hit `Enter` to save the changes.
### **Step 5: Restart MongoDB**
After enabling authentication, you need to restart the MongoDB service for the changes to take effect.
1sudo systemctl restart mongod
### **Step 6: Connect with Authentication**
Now that authentication is enabled, you will need to provide a username and password when connecting to MongoDB.
To connect to MongoDB as the newly created admin user:
1mongosh "mongodb://admin_user:your_secure_password@localhost:27017/admin"
- **admin_user**: The username you created.
- **your_secure_password**: The password you set.
- **localhost**: The hostname of your MongoDB server (or the IP address if you're connecting remotely).
- **27017**: The default MongoDB port.
#### **For Remote Connections:**
If you are connecting from a remote machine, use the server's IP address:
### **Step 7: Verify the User Creation**
Once connected to MongoDB with the new admin user, you can verify the user creation by running:
1db.getUsers()
This will list all users for the current database.
-