MongoDB is a document database with the scalability and flexibility in mind. It is a distributed database at its core – so scaling and high availability are built in and easy to use.
Installation
Use the following command to import the MongoDB public GPG Key
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4
Then use the following command:
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
Run following command for getting the updates:
sudo apt-get update
Then install the MongoDB using command:
sudo apt-get install -y mongodb-org
You can restart the service by using:
sudo service mongod restart
To start use:
sudo service mongod start
And to stop:
sudo service mongod stop
To enable the service after reboot:
sudo systemctl enable mongodb
Now open /etc/systemd/system/mongodb.service file in any editor. Like, to edit it with vim use following command.
sudo vim /etc/systemd/system/mongodb.service
Add following lines to the file /etc/systemd/system/mongodb.service:
#Unit contains the dependencies to be satisfied before the service is started.
[Unit]
Description=MongoDB Database
After=network.target
Documentation=https://docs.mongodb.org/manual
# Service tells systemd, how the service should be started.
# Key `User` specifies that the server will run under the mongodb user and
# `ExecStart` defines the startup command for MongoDB server.
[Service]
User=mongodb
Group=mongodb
ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf
# Install tells systemd when the service should be automatically started.
# `multi-user.target` means the server will be automatically started during boot.
[Install]
WantedBy=multi-user.target
Enable authentication
Use following commands to access mongo db:
mongo
Switch to ‘admin’ database:
use admin
Use following command to create your user: (set your password in place of ’test pass’)
db.createUser({user:"admin", pwd:"testpass", roles:[{role:"root", db:"admin"}]})
Update file /etc/systemd/system/mongodb.service with following line:
ExecStart=/usr/bin/mongod --quiet --auth --config /etc/mongod.conf
Update /etc/mongodb.conf with following line
security:
authorization: enabled
Restart mongoldb service, and you are done.
If you want to enable remote access– then open file /etc/mongod.conf and make changes in following lines:
net:
port: 27017
bindIp: 0.0.0.0 #This will make the server available from any ip. To restrict access from specific IP, set that IP here