MongoDB is the most popular NoSQL database in the world used by thousands of companies including Facebook, Google, and Coinbase. It is a free and open-source document-based database, that stores the data in BSON (short for Binary JSON) format.

BSON is the binary encoding of JSON-like documents that MongoDB uses for storing data. MongoDB is schemaless, which means you do not need to predefine the schema and data structure can be changed in the future.

In this tutorial, we will learn how to install and configure the latest version of MongoDB 4.2 Community Edition on the Ubuntu 18.04 machine using the official MongoDB repositories.

Prerequisites

Before following the next steps in this tutorial, make sure that you are logged in a user with sudo privileges.

Installing MongoDB

Although MongoDB package is already included in Ubuntu's public repositories, it is not maintained by the MongoDB team. The official repository provides an up-to-date version of MongoDB and is the recommended way of installing it.

Here is what the MongoDB team say:

The mongodb-org package is officially maintained and supported by MongoDB Inc. and kept up-to-date with the most recent MongoDB releases. This installation procedure uses the mongodb-org package.

The mongodb package provided by Ubuntu is not maintained by MongoDB Inc. and conflicts with the mongodb-org package. To check if Ubuntu’s mongodb package is installed on the system, run sudo apt list --installed | grep mongodb. You can use sudo apt remove mongodb and sudo apt purge mongodb to remove and purge the mongodb package before attempting this procedure.

Follow the below steps to install the latest version of MongoDB from official repository on your Ubuntu server.

Step 1 — Enabling MongoDB Repository

First of all, import the MongoDB public key used by the package management system using the following command:

$ wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -

Once the key is imported, add the MongoDB repository to sources list:

$ echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list

If you get an error that says add-apt-repository command not found, install the software-properties-common package.

To install an older/newest version of MongoDB, just replace 4.2 in above command with your preferred version.

Step 2 — Updating Packages List

Run the following command to update the local package database:

$ sudo apt update

Step 3 — Installing MongoDB Pacakges

Now that the repository is enabled and the local package database is updated, it is time to install MongoDB packages. Just issue the following command to install the latest stable version:

$ sudo apt install -y mongodb-org

The above command will install the following packages on your Ubuntu machine as a part of mongodb-org meta package:

  • mongodb-org-server — Contains the mongod daemon, associated init scripts, and configurations.
  • mongodb-org-mongos — Contains the mongos daemon.
  • mongodb-org-shell — Contains the mongo shell, an interactive JavaScript interface to MongoDB. It is used to perform administrative tasks as well as run queries and operations through the command line.
  • mongodb-org-tools — Contains various MongoDB tools for to importing and exporting data, statistics, as well as other utilities.

Step 4 — Starting MongoDB

The installation process automatically starts the MongoDB service. But you can run the following command to verify that the service is up and running:

$ sudo service mongod status

You should see the following output:

● mongod.service - MongoDB Database Server
   Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
   Active: active (running) since Sat 2019-09-07 21:36:30 PKT; 1s ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 22113 (mongod)
   Memory: 155.2M
   CGroup: /system.slice/mongod.service
           └─22113 /usr/bin/mongod --config /etc/mongod.conf

Step 5 — Verifying MongoDB Installation

To further verify that whether the installation has completed successfully, we can connect to the MongoDB database server using the mongo tool and execute a diagnostic command:

$ mongo --eval 'db.runCommand({ connectionStatus: 1 })'

The output will look like below:

MongoDB shell version v4.2.0
connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("d9868000-a7ab-47fa-aa97-70ee0e8b242d") }
MongoDB server version: 4.2.0
{
	"authInfo" : {
		"authenticatedUsers" : [ ],
		"authenticatedUserRoles" : [ ]
	},
	"ok" : 1
}

A value of 1 for the ok field shows that the server is running properly.

Managing MongoDB Service

MongoDB is installed as a systemd service. It means that you can manage it using standard systemd commands like systemctl or service on Ubuntu.

To start the MongoDB service, run the following command:

$ sudo service mongod start

To check the current status of the MongoDB service, issue the following command:

$ sudo service mongod status

You can stop the service anytime by typing:

$ sudo service mongod stop

If you want to restart the service, use the following command:

$ sudo service mongod restart

By default, MongoDB is configured to start automatically when the server starts. You can disable the automatic startup by typing:

$ sudo systemctl disable mongod

If you want to enable the automatic startup again, just type:

$ sudo systemctl enable mongod

Configuring Firewall (Optional)

By default, MongoDB server is configured to listen on port 27017 for local requests. If you want to use the MongoDB server locally with an application running on the same server, it is perfectly fine. However, if you want to be able to access the server from anywhere, you have to allow the remote access by running the following command:

$ sudo ufw allow 27017

However, allowing access to the MongoDB server from anywhere gives anyone unrestricted access to the database server and its data. So it is a good idea to explicitly allow access to certain trusted IP addresses only on MongoDB's default port by using the following command:

$ sudo ufw allow from your_trusted_server_ip/32 to any port 27017

To verify the changes in firewall settings, type:

$ sudo ufw status

You should see the port 27017 is allowed to receive incoming traffic in the output.

Although the port is open now, the MongoDB server is still listening on the local address 127.0.0.1. To enable remote connections, you must add your server’s public IP address to the mongod.conf file.

Open the MongoDB configuration file in the editor:

$ sudo nano /etc/mongo.conf

Add your server's IP address to net.bindIp:

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,your_trusted_server_ip

Make sure you add a comma between existing local address and the one you added. Save the file and restart the MongoDB server by typing:

$ sudo service mongod restart

MongoDB is now listening for remote connections from the server you just added the IP address.

Conclusion

That's all we had for today. You have learned how to install and configure MongoDB Community Edition version 4.2 on the Ubuntu 18.04 LTS server through the official MongoDB repositories.

Check out The MongoDB 4.2 Manual to learn more about MongoDB key concepts, query language, operational and administrative guides, and more.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.