# How to Install MongoDB on Ubuntu 18.04

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 7, 2019, updated Feb 7, 2021. Topics: Ubuntu, DevOps, MongoDB.
Canonical URL: https://attacomsian.com/blog/install-mongodb-ubuntu-18-04

> A step-by-step guide to install and configure MongoDB 4.2 community edition on Ubuntu 18.04 server.

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](http://bsonspec.org/) (short for **Binary JSON**) format. 

BSON is the binary encoding of [JSON-like](https://attacomsian.com/blog/what-is-json) 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](https://attacomsian.com/blog/create-user-with-sudo-privileges-on-ubuntu) on a Ubuntu 8.04 machine (get one from [DigitalOcean](https://attacomsian.com/go/digitalocean)).

## 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](https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/#install-mongodb-community-edition-using-deb-packages):

> *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.*
> <br/>
> <br/>
> *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 the official repository on your Ubuntu server.

### Step 1 &mdash; Enabling MongoDB Repository

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

```bash
$ 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:

```bash
$ 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 the above command with your preferred version.

### Step 2 &mdash; Updating Packages List

Run the following command to update the local package database:

```bash
$ sudo apt update
```

### Step 3 &mdash; Installing MongoDB Packages

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:

```bash
$ 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` &mdash; Contains the `mongod` daemon, associated init scripts, and configurations.
* `mongodb-org-mongos` &mdash; Contains the `mongos` daemon.
* `mongodb-org-shell` &mdash; 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` &mdash; Contains various MongoDB tools for importing and exporting data, statistics, as well as other utilities.

### Step 4 &mdash; 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:

```bash
$ sudo service mongod status
```

You should see the following output:

```bash
● 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 &mdash; Verifying MongoDB Installation

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

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

The output will look like below:

```bash
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:

```bash
$ sudo service mongod start
```

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

```bash
$ sudo service mongod status
```

You can **stop** the service anytime by typing:

```bash
$ sudo service mongod stop
```

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

```bash
$ sudo service mongod restart
```

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

```bash
$ sudo systemctl disable mongod
```

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

```bash
$ 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:

```bash
$ 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:

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

To verify the changes in firewall settings, type:

```bash
$ 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:

```bash
$ sudo nano /etc/mongo.conf
```

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

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

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

```bash
$ 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](https://docs.mongodb.com/v4.2/) to learn more about MongoDB key concepts, query language, operational and administrative guides, and more.
