MongoDB is one of the most popular non-relational or NoSQL open source DBMS. It manages the storage and representation of the data in Documents provided in JSON format and organized in Collections. It is particularly suitable in all those cases where greater scalability, as well as speed and ease of expansion, and access to data are needed.
In this tutorial you will learn how to install and manage MongoDB on a server with Linux Ubuntu 18.04 distribution.
First, connect to your server via an SSH connection. If you haven’t done so yet, following our guide is recommended to connect securely with SSH. In case of a local server, go to the next step and open the terminal of your server.
MongoDB installation
To be sure you to download the latest most updated version of MongoDB, update the repositories of the distribution, and start the installation:
$ sudo apt-get update && sudo apt-get install mongodb
As default configuration, MongoDB will automatically start when accessing the system. To disable this option use the following command:
$ sudo systemctl disable mongodb
While to re-enable the automatic start type:
$ sudo systemctl enable mongodb
Managing the MongoDB service
To check the status of the service type:
$ 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 Sat 2019-08-13 03:43:44 UTC; 5min 27s ago
Docs: man:mongod(1)
Main PID: 2208 (mongod)
Tasks: 27 (limit: 1200)
CGroup: /system.slice/mongodb.service
└─2208 /usr/bin/mongod --unixSocketPrefix=/run/mongodb --config /etc/mongodb.conf
An output like the one above will be displayed. Use it to check if the service is running.
To start the service:
$ sudo systemctl start mongodb
To stop the service:
$ sudo systemctl stop mongodb
To restart the service:
$ sudo systemctl restart mongodb
Database status
To check the status of the database connection, type the following diagnostic command:
$ mongo --eval 'db.runCommand({ connectionStatus: 1 })'
With this command the connection parameters, version of the server and its status will be displayed.
External connection
To enable an external connection to your MongoDB instance, enable the listening by indicating your public IP address.
Open the MongoDB configuration file:
$ sudo nano /etc/mongodb.conf
Then, change the bind_ip parameter to add your server's public IP address to it:
bind_ip = 127.0.0.1,<SERVER.IP>
At this point, save the file and restart the MongoDB service:
$ sudo systemctl restart mongodb
In case of a firewall on your system, enable the traffic for MongoDB.
When using the UFW firewall, enable the connection to your instance with the command:
If the port number for MongoDB has been changed, replace 27017 with the port that is currently being used.
N.B. To allow access only to a specific IP address, use the command:
$ sudo ufw allow from <SERVER.IP>/32 to any port 27017