В предыдущей статье мы научились устанавливать mongodb на Ubuntu. В этой статье я расскажу как создать пользователя в mongodb.
MongoDB содержит огромное количество ролей, создавая пользователя, вы можете назначать ему одну или несколько ролей, тем самым регулируя доступ к своей базе данных.
Если у вас еще не включена авторизация в конфиге, то вам достаточно присоединиться к mongodb
И добавить пользователя, данный пользователь будет иметь root права
После это выйти из базы данных и зайти с помощью юзера и пароля
Если вы не укажите параметр —password, то надо будем ввести пароль позже. Данный вид аутентификации предпочтителен.
Но добавление данного пользователя бесолезено, потому что у нас не включена авторизация.
- Включение авторизации на mongodb
- Создание пользователя mongodb с включенной авторизацией
- Important
- mongosh Method
- Tip
- Important
- Warning
- Tip
- Tip
- Tip
- Tip
- Tip
- Note
- Tip
- Introduction
- Prerequisites
- Add MongoDB Public Key
- Create Repository Configuration For Mongodb 4
- Install MongoDB 4. 0 on Ubuntu 18
- Managing MongoDB Service
- Checking MongoDB Service
- Create MongoDB root and admin users
- Generate Random Password Using Command Line
- Enabling Authentication on MongoDB 4
- Updating mongod.service file
- Updating mongodb.conf file
- Uninstall MongoDB 4. 0 on Ubuntu 18
- MongoDB 4. 0 References
- Conclusion
- Linux CentOS Server Configurations (MongoDB)
- Step 5: Create Admin User for use with your MongoDB instance
- Step 6: Enable Authentication for the MongoDB Server
- Step 7: Testing that everything works as expected (so far)
- Step 8: Creating a new database with the admin user
- Step 8 — Option 1: Create a new ‘root’ user
- Step 8 — Option 2: Modify existing ‘admin’ user to have the additional role of ‘root’
- Step 9: Changing user passwords
- This completes the MongoDB Server Installation and Configuration Guide for Red Hat 8 / CentOS 8
- — If you are still having issues with your installation, please reach out to members of the MTT Training Team for assistance
- CONTINUED Learning
- In The Next Section:
- Steps
- Troubleshooting
Включение авторизации на mongodb
Прежде чем создать пользователя в mongodb, лучше включить авторизацию, для этого необходимо либо прописать в конфиге
security: authorization: enabled Полный конфиг у нас будет выглядеть так
storage: dbPath: "/path/to/mongodata"
systemLog: path: "/path/to/logs/mongod.log" logAppend: true destination: "file"
net: bindIp : localhost
processManagement: fork : true
security: authorization: enabled Либо запускать mongod с параметром —auth
Если у вас не добавлено ни одного пользователя в mongodb, то после этого, вы сможете подключиться без авторизации только с localhost, для создания первого юзера. После создания первого юзера, вы не сможете подключится к серверу без авторизации даже с localhost. Это правильно называется Localhost Exception
Создание пользователя mongodb с включенной авторизацией
Для того, чтобы создать пользователя с включенной авторизацией, но без единого пользователя в бд, убедитесь что у вас в конфиге установлено
net: bindIp : locahost Далее подключитесь к mongodb
И создайте пользователя mongodb. Первый пользователь с включенной авторизацией в конфиге, должен иметь права администратора и возможность создавать других пользвотелей.
Теперь к бд можно подключится с данным пользователем.
Дополнительную информацию вы всегда можете найти на сайте с официальной документацией
db.createUser(user, writeConcern)Important
mongosh Method
This page documents a method. This is not
the documentation for database commands or language-specific drivers,
such as Node.js.For MongoDB API drivers, refer to the language-specific
MongoDB driver documentation.mongo shell v4.4
Tip
Or you can specify the role with a document, as in:
To specify a role that exists in a different database, specify the role
with a document.
Important
Warning
MongoDB does not store the password in cleartext. The password
is only vulnerable in transit between the client and the
server, and only if TLS transport encryption is not enabled.
Tip
the
readWriterole on theproductsdatabase
Tip
Tip
Tip
Tip
Note
Tip
If the authenticationMechanisms parameter is set, the
mechanisms field can only include values specified in the
authenticationMechanisms parameter.
In this tutorial we learn how to install MongoDB 4.0 on Ubuntu 18.04. We will learn basic configuration of MongoDB 4.0.
Tags:
Introduction
In this tutorial, we will learn how to install MongoDB 4.0 on Ubuntu 18.04 LTS (Bionic Beaver). We will also learn to configure and secure our MongoDB 4.0 installation
Prerequisites
- Ubuntu 18.04 LTS (Bionic Beaver) with sudo access.
The tutorial to install MongoDB 4.0 also available for different operating systems below:
Add MongoDB Public Key
First of all, let’s add the MongoDB public key. This key is used by package management tool like apt to ensure the consistency and authenticity of the package.
wget -qO - https://www.mongodb.org/static/pgp/server-4.0.asc | sudo apt-key add -The output should be similar to the text below
Create Repository Configuration For Mongodb 4
Create new file /etc/apt/sources.list.d/mongodb-org-4.0.list that contain MongoDB 4.0 repository info using the command below.
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list > /dev/nullReload apt package database using the command below.
sudo apt-get updateInstall MongoDB 4. 0 on Ubuntu 18
To install the latest stable version of MongoDB 4.0 you can use the command below.
sudo apt-get install mongodb-orgAt the time of this writing, the latest stable version of MongoDB 4.0 is 4.0.25.
To install a previous stable version of MongoDB 4.0 you need to specify a version for each package. For example, if you need to install MongoDB 4.0.24 you can use the command below.
sudo apt-get install -y \ mongodb-org=4.0.24 \ mongodb-org-server=4.0.24 \ mongodb-org-shell=4.0.24 \ mongodb-org-mongos=4.0.24 \ mongodb-org-tools=4.0.24Managing MongoDB Service
After MongoDB Server has been installed, we can check MongoDB service using the command below.
sudo service mongod statusWe can also use systemctl command to check status of mongod service.
sudo systemctl status mongodWe will get output similar to below which inform that mongod is not running.
To start MongoDB service we can use command below:
sudo service mongod startor we can also use systemctl to start MongoDB service
sudo systemctl start mongodWe will see output similar to output below
MongoDB service already started but it’s not enabled by default by seeing this line
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)Let’s enable MongoDB service on boot by running
sudo systemctl enable mongodbNow if we check MongoDB service status we will see that the service is enabled.
Checking MongoDB Service
Beside using service or systemctl command, we can use multiple tools to check status of MongoDB service.
To check where MongoDB service listening to we can use netstat
sudo netstat -naptu | grep 27017In the command above, we grep MongoDB default port 27017.
As alternative we can also grep mongod application name
sudo netstat -naptu | grep mongodWe can also use ss to do similar check like netstat
ss -at | grep 27017If we want to know MongoDB process details we can use ps command
ps aux | grep -m1 mongodWe use option -m1 to so we only show the first line of grep since grep will also our grep process that contain mongod word.
top -u mongodbCreate MongoDB root and admin users
mongo admindb.createUser({user:"root", pwd:"changemeplease123123123", roles:[{role:"root", db:"admin"}]})Generate Random Password Using Command Line
Generate random string for password on command line using command below
uuidgen | sha256sum | awk {'print $1'}Besides using awk we can also use cut utility to only get the randomly generated password.
uuidgen | sha256sum | cut -d ' ' -f 1Enabling Authentication on MongoDB 4
There are two ways to enable MongoDB authentication, by updating systemd service file or updating mongodb.conf file.
Use the second method since mongodb service file might be overwritten by apt when we upgrade mongodb package.
Updating mongod.service file
Open /lib/systemd/system/mongod.service file.
ExecStart=/usr/bin/mongod --config /etc/mongod.confReplace the line with
ExecStart=/usr/bin/mongod --auth --config /etc/mongod.confReload systemd daemons using command below
sudo systemctl daemon-reloadRestart MongoDB service using command below
sudo systemctl restart mongodUpdating mongodb.conf file
Open «/etc/mongodb.conf file
#security:Replace it with
security: authorization: enabledRestart MongoDB service to enable authentication
sudo service mongod restartmongo -uadmin admin -pUninstall MongoDB 4. 0 on Ubuntu 18
In this section we’ll learn how to uninstall MongoDB 4.0 from Ubuntu 18.04. Please be really careful when running command on this section.
Before we uninstall MongoDB 4.0 we need to stop MongoDB service first.
sudo service mongodb stopTo uninstall MongoDB 4.0 we can use command below
sudo apt-get purge mongodb-org*The command above only remove MongoDB packages.
We can run the command below to remove MongoDB 4.0 log directory.
sudo rm -r /var/log/mongodbTo remove MongoDB data directory use command below
WARNING : command below will remove your data and cannot be restored. be very very very careful when you’re running command below.
sudo rm -r /var/lib/mongodbMongoDB 4. 0 References
You can find references related to MongoDB 4.0 below
Conclusion
At the end we learned how to uninstall MongoDB 4.0 from Ubuntu 18.04.
Now you can start building your application using MongoDB as a database.
Linux CentOS Server Configurations (MongoDB)
Step 5: Create Admin User for use with your MongoDB instance
Open a mongo shell
Switch to the default databases ‘admin’ included with the default installation of your fresh MongoDB server
Now, copy and paste the following lines into the mongo shell that you just opened
- !!!IMPORTANT NOTE!!!: Change your username or password as necessary — but the remainder of this doc will use the following assumptions for the admin user:
- You should now have a user with the name ‘admin’ and a password of ‘admin’
- To show your newly created user, run the following command in the mongo shell:
- If you get an error similar to: ‘uncaught exception: Error: command usersInfo requires authentication :’ — we will be «fixing» this in the next step
now exit the mongo shell
Step 6: Enable Authentication for the MongoDB Server
- We need to edit the file
/etc/mongod.confto enable authentication using a user with sudo privileges (or root user)
- If you are using the nano text editor, you can enable constant cursor / show line numbers by using the Alt+C key combination. Your file may be different, but on most fresh mongodb installations running on CentOS 8, the commented line of
(this is usually on or near line 32).
- Under the commented the #security line (or remove the commented line it and) paste / modify it as follows:
Save and Close the file
/etc/mongod.confwith your changesRestart the mongod service in order to apply the new configuration you just added
sudo systemctl restart mongod
Note: If you get errors while trying to resart, please delete the “white spacing” from the previously edited /etc/mongod.conf file and leave ONLY 2 spaces under
security:and beforeauthorization: “enabled”without any whitespace at the end of either lines (some text editors use whitespaces as special characters, like tabs, which may cause issues with the configuration file – you can manually type out the security code snippet above, save the file, then restart mongod again, just to be sure)Check for any errors or warnings in the mongod service and verify that the service is ‘active (running)’
sudo systemctl status mongod
Verify that you are able to login with your admin user that you created in Step 6 by starting a mongo shell again and testing that authentication is working properly
From the mongo shell, switch to use the admin database
Now run the command to show users again
If authentication is properly enabled, You SHOULD get an ERROR similar to:
shell version v4
This is expected. This verifies that authentication is now enabled.
Now we log in as our admin user using authentication, like so (while still in the mongo shell):
The output should be ‘1’ — for success (if you used a different username and password in Step 4 during admin user creation, use that here instead). Now you can run the show users command again to display the users in the mongo shell
You should see an output similar to the following (your UUID will be different):
Now we exit the mongo shell
Step 7: Testing that everything works as expected (so far)
At this point, you can run the following command to update and reboot your system to verify that you will have your MongoDB Server running at boot time with the following command
- !!!NOTE!!!: THIS WILL REBOOT YOUR SYSTEM — SAVE YOUR WORK AND BROWSER BOOKMARKS FIRST
sudo dnf update
If you don’t want to reboot right now, you can just run the following commands to stop and start the mongod service which will imitate the same as a reboot (only you with still need to verify the mongod service starts at boot time when you reboot later).
sudo systemctl stop mongod
sudo systemctl start mongod
Now we check that the mongod service is running and there are no warnings or errors:
sudo systemctl status mongod
Now we verify that mongod is running on the expected port of 27017 (we can change this later in more advanced configurations — we are only just getting started here)
The above command should produce a similar output to the following:
The above output shows that mongod is running on 127.0.0.1 (localhost) at port 27017 as expected
Now we test that we are able to log in with our newly created admin user from previous steps be entering the mongo shell again
switch to the admin database
Run the ‘show users’ command again to verify that you are NOT allowed to see the users because you have enabled authentication
Now we authentication our admin user with:
The output should be ‘1’ for success. Let’s try the ‘show users’ command again since we are now authenticated
You should now see the details for the users in the database are present
- In our case it should only be the admin user.
- The summary for this Testing Step show look similar to the following:
shell version v4
now we can exit the mongo shell
Step 8: Creating a new database with the admin user
While we now have access to the existing default databases included with our fresh MongoDB Server installation on our CentOS 8 instance, we do not yet have the ability to create new databases and add collections to those new databases through tools such as Compass or Robo 3T (aka RoboMongo). Further configuration is required, as follows:
We have a few different options:
1) Create a new ‘root’ user for MongoDB that has root privileges for creation of new Databases on our MongoDB Server
2) Modify the existing ‘admin’ user that we created earlier to also have root level access to create new databases
This guide will show you both options, though security is paramount — so I will also show you how to modify your passwords as a final step so that you can customize your your passwords (and user names as well, should you choose)
Step 8 — Option 1: Create a new ‘root’ user
Start the mongo shell
switch to the admin database
authentication the existing ‘admin’ user
Copy/Paste the following into the mongo shell prompt after you have authenticated (modify if necessary)
Use should see output similar to the following:
Use should see output similar to the following:
You have now created a ‘root’ user with a role of ‘root’ — you can ‘show user’ to verify — you can also exit the mongo shell now
Step 8 — Option 2: Modify existing ‘admin’ user to have the additional role of ‘root’
Start the mongo shell
switch to the admin database
authentication the existing ‘admin’ user
Copy/Paste the following into the mongo shell prompt after you have authenticated (modify if necessary)
You have now added the root role to the existing admin user — exit the mongo shell
Wrapping up Options 1 + 2: Repeat Step 7 now, using either / or / both of the following during the authentication portion (remember to use your user names and passwords if you used your own and not mine)
Login and Authenticate with the ‘admin’ user
Login and Authenticate with the ‘root’ user
When you are in the mongo shell, are in the admin database (use admin) and authenticated as your preferred «root user» and run the «show users» command and you will SHOULD get output similar to the following (this example includes the results of both options):
You should now be able to create new databases with the chosen option for your user that you endowed with the ‘root’ role — exit the mongo shell
Step 9: Changing user passwords
Start the mongo shell
switch to the desired database — in our case its ‘admin’
Authenticate your user — in our example we will use ‘admin’ and assume ‘admin’ as the password
- After you get an output of ‘1’ (which repesents «successful authentication»), you have 2 options to change your password:
Option 1 — prompt for a password (eg. in the event you have people looking at your screen and do not want to reveal the password you are changing to) — NOTE: You will not be able to your own password! Make sure you type carefully!!! There is no confirmation or second entry!
Option 2 — Include your password in the same line:
NOTES: Other users with a «role» of «root» (and other elevated privilege roles) can modify other users passwords! With great power comes great responsibility!
Final Notes: you can also hide your password during authentication by using the following
This will protect any eyeballs from seeing your password on your screen during authentication
This completes the MongoDB Server Installation and Configuration Guide for Red Hat 8 / CentOS 8
— If you are still having issues with your installation, please reach out to members of the MTT Training Team for assistance
CONTINUED Learning
MongoDB User Roles, explained
Check for the Installation of MongoDB Database Tools on Linux CentOS / Red Hat
sudo dnf list installed mongodb
In The Next Section:
asked Apr 11, 2014 at 3:30
- Stop your MongoDB instance
- Remove the —auth and/or —keyfile options from your MongoDB config to disable authentication
- Start the instance without authentication
- Edit the users as needed
- Restart the instance with authentication enabled
answered Apr 16, 2014 at 1:37
4 silver badges3 bronze badges
- Open the MongoDB configuration file using
sudo(sudo vi mongodb.conf).
The file can be found in/etc/folder.- Comment
"auth = true".- Stop the MongoDB service (
sudo service mongod stop)- Start the MongoDB service (
sudo service mongod start)use admin db.createUser({user:"admin",pwd:"password",roles:[{role:"root",db:"admin"}]});Go back and uncomment
"auth=true". Stop and Start/Restart the mongodb service.
3 silver badges10 bronze badges
answered Dec 29, 2016 at 22:37
If you use a replica set with a
keyfileSecurity between members of the replica set using Internal
AuthenticationKeyfile is used for auth in replication.
security: keyFile: <path-to-keyfile> replication: replSetName: <replicaSetName>mongo -u __system -p "$(tr -d '\011-\015\040' < path-to-keyfile)" --authenticationDatabase localanswered Sep 4, 2017 at 13:23
6 gold badges31 silver badges58 bronze badges
Steps
- Connect to the machine that was hosting my MongoDB instance
- Open the MongoDB configuration file found in
/etc/folder using:sudo nano mongod.conf- Comment out the following code like so:
# security: # authorization: enabled- Stop the MongoDB service:
sudo service mongod stop- Start the MongoDB service:
sudo service mongod start- Connect to the database using Robo3T or equivalent. With a connection to the admin collection, create a new admin superuser:
db.createUser({ user:"admin", pwd:"password", roles:[{role:"root", db:"admin"}] });- Go back and uncomment the lines from step 3. Then repeat steps 4 and 5.
- You should now be able to authenticate with the new user you created in step 6 and have full access to the database.
Troubleshooting
- If for whatever reason, after trying to restart your mongo service, you cannot connect to it, you can make sure the service properly started with:
systemctl --type=service --state=active. If it has started, it will be in the list asmongod.service. - Mongo logs can also be found at
/var/log/mongodb/mongodb.logbut this is less likely to be helpful in this situation.
answered Sep 13, 2022 at 16:46

sudo service mongod stop
mv /data/admin.* .
sudo service mongod startanswered Apr 11, 2014 at 3:41

2 gold badges5 silver badges7 bronze badges
I can start MongoDB as $sudo service mongod start. When I start without sudo it gives me this error:
/etc/init.d/mongod: line 58: ulimit: open files: cannot modify limit: Operation not permitted
/etc/init.d/mongod: line 60: ulimit: max user processes: cannot modify limit: Operation not permitted
Starting mongod: runuser: may not be used by non-root users$sudo chown -R nonRootUser:nonRootUser [directory]2) I’ve deleted mongod.lock files
3) I’ve run --repair too
It still gives me the same error.
I also tried
$mongod --fork --logpath /var/log/mongodb.log
about to fork child process, waiting until server is ready for connections.
forked process: 18566
ERROR: child process failed, exited with error number 1mongod.log file says this:
2016-03-17T15:03:49.053+0000 I NETWORK [initandlisten] waiting for connections on port 27017
2016-03-17T15:03:54.144+0000 I CONTROL [signalProcessingThread] got signal 15 (Terminated), will terminate after current cmd endsIt’s Amazon Linux. I am able to start it like this $mongod, but I want to run it as daemon so it runs continuously.







