How to Install MongoDB 5 on Ubuntu 18.04

MongoDB is an open-source document database used in many modern web applications. and MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of using tables and rows as in the traditional relational databases.

Installing MongoDB on Ubuntu 18.04.

sudo apt update

apt install mongoDB 

Output:

root@vps:~# apt install mongodb
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:
  libboost-filesystem1.65.1 libboost-iostreams1.65.1
  libboost-program-options1.65.1 libboost-system1.65.1
  libgoogle-perftools4 libpcrecpp0v5 libsnappy1v5
  libstemmer0d libtcmalloc-minimal4 libyaml-cpp0.5v5
  mongo-tools mongodb-clients mongodb-server
  mongodb-server-core

Managing the MongoDB Service.

To start a MongoDB service.

sudo systemctl start mongodb

To enable MongoDB service.

sudo systemctl enable mongodb   

You can verify its status using the systemctl command.

sudo systemctl status mongodb

Output:

root@vps:~# systemctl status mongodb
● mongodb.service - An object/document-oriented database
   Loaded: loaded (/lib/systemd/system/mongodb.service; enabled
   Active: active (running) since Tue 2021-10-26 15:48:37 UTC; 
     Docs: man:mongod(1)
 Main PID: 8922 (mongod)
    Tasks: 23 (limit: 1106)
   CGroup: /system.slice/mongodb.service
           └─8922 /usr/bin/mongod --unixSocketPrefix=/run/mongo

Enable Remote MongoDB Access on Firewall

By default MongoDB runs on port 27017, to allow access from everywhere you can use it.

sudo ufw allow 27017

Output:

root@vps:~# sudo ufw allow 27017
Rules updated
Rules updated (v6)

But enabling access to MongoDB from everywhere gives unrestricted access to the database data. So, it’s better to give access to a specific IP address location to default MongoDB’s port using the following command.

sudo ufw allow from your_server_IP/32 to any port 27017 

Output:

root@vps:~# sudo ufw allow from Your_Ip/32 to any port 27017 
Rules updated

To allow remote MongoDB connections, you need to add your server IP address to /etc/mongodb.conf configuration file as shown.

vim /etc/mongodb.conf

Output:

bind_ip = 127.0.0.1,your_server_ip
#port = 27017

To restart a MongoDB service.

sudo systemctl restart mongodb.service

Access MongoDB Shell.

You can now access MongoDB’s shell by using the following command.

mongo

Output:

root@vps:~# mongo
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
  http://docs.mongodb.org/
Questions? Try the support group
  http://groups.google.com/group/mongodb-user
Server has startup warnings: 
2021-10-26T15:56:28.571+0000 I STORAGE  [initandlisten] 
2021-10-26T15:56:28.571+0000 I STORAGE  [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2021-10-26T15:56:28.571+0000 I STORAGE  [initandlisten] **          See http://dochub.mongodb.org/core/prodnotes-filesystem
2021-10-26T15:56:29.960+0000 I CONTROL  [initandlisten] 
2021-10-26T15:56:29.960+0000 I CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-10-26T15:56:29.960+0000 I CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2021-10-26T15:56:29.960+0000 I CONTROL  [initandlisten] 
>

Once you have connected to the mongo shell, you can list all available databases with the following command.

show dbs

Output:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

Creating MongoDB Admin User.

use admin     

db.createUser({user:"root", pwd:"=@!#@%$admin1", roles:[{role:"root", db:"admin"}]})

Output:

 > db.createUser({user:"root", pwd:"=@!#@%$admin1", roles:[{role:"root", db:"admin"}]})
Successfully added user: {
  "user" : "root",
  "roles" : [
    {
      "role" : "root",
      "db" : "admin"
    }
  ]
}
> 

To list MongoDB users created.

show users

Output:

> show users
{
  "_id" : "admin.root",
  "userId" : UUID("a841107f-e63f-4a1a-a283-c969640b9528"),
  "user" : "root",
  "db" : "admin",
  "roles" : [
    {
      "role" : "root",
      "db" : "admin"
    }
  ]
}
> 

Configuring Authentication for MongoDB.

The MongoDB instance was started without the --auth command line option. You need to enable authentication of users by editing /lib/systemd/system/mongod.service file

sudo vim /lib/systemd/system/mongodb.service 

Under the [Service] config section, find the parameter ExecStart.

ExecStart=/usr/bin/mongod --unixSocketPrefix=${SOCKETPATH} --config ${CONF} $DAEMON_OPTS

Change it to the following.

EnvironmentFile=-/etc/default/mongodb
Environment=CONF=/etc/mongodb.conf
Environment=SOCKETPATH=/run/mongodb
ExecStart=/usr/bin/mongod  --auth --unixSocketPrefix=${SOCKETPATH} --config ${CONF} $DAEMON_OPTS

For the changes to come into effect, reload the system and restart MongoDB.

systemctl daemon-reload

sudo systemctl restart mongodb  

sudo systemctl status mongodb   

Output:

root@vps:~# sudo systemctl status mongodb   
● mongodb.service - An object/document-oriented database
   Loaded: loaded (/lib/systemd/system/mongodb.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2021-10-26 16:03:19 UTC; 4s ago
     Docs: man:mongod(1)
 Main PID: 9388 (mongod)
    Tasks: 23 (limit: 1106)
   CGroup: /system.slice/mongodb.service
           └─9388 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf

Oct 26 16:03:19 vps.server.com systemd[1]: Stopped An object/document-oriented database.
Oct 26 16:03:19 vps.server.com systemd[1]: Started An object/document-oriented database.

Now when you try to connect to MongoDB, you must authenticate yourself as a MongoDB user.

mongo -u "root" -p --authenticationDatabase "admin"

Output:

root@vps:~# mongo -u "root" -p --authenticationDatabase "admin"
MongoDB shell version v3.6.3
Enter password:
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.6.3

Switch to the admin database.

use admin

Output:

> use admin
switched to db admin

List the users and see if you can list the created user.

show users

Output:

> show users
{
  "_id" : "admin.root",
  "userId" : UUID("a841107f-e63f-4a1a-a283-c969640b9528"),
  "user" : "root",
  "db" : "admin",
  "roles" : [
    {
      "role" : "root",
      "db" : "admin"
    }
  ]
}
> 

Done.