Wed. Oct 16th, 2024

To enable authentication and create a user in MongoDB, you’ll need to follow these steps:

Step 1: Enable Authentication

Open the MongoDB configuration file:

  • The MongoDB configuration file is typically located at /etc/mongod.conf on Linux systems. The exact location might differ depending on your installation method and operating system.
  • Open the file using a text editor. For example
sudo nano /etc/mongod.conf

Enable authentication:

  • In the configuration file, find the security section and add the following line:
security:
  authorization: enabled

If the security section doesn’t exist, you can add it.

Step 2: Create an Administrative User

Start the MongoDB shell:

  • You can start the MongoDB shell by running:
mongo

Switch to the admin database:

  • Switch to the admin database where administrative users are usually stored:
use admin

Create an admin user:

  • Use the following command to create a new administrative user with the userAdminAnyDatabase role:
db.createUser({
  user: "admin",
  pwd: "adminPassword",
  roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})

Replace "admin" with your desired username and "adminPassword" with a strong password.

Exit the MongoDB shell:

  • Type exit to leave the MongoDB shell.

Restart MongoDB:

  • After saving the changes to the configuration file, restart MongoDB to apply the changes:
sudo systemctl restart mongod

Leave a Reply

Your email address will not be published. Required fields are marked *