---
title: "How to Install MongoDB on Ubuntu Linux"
description: "Learn the ins-and-outs of installing NoSQL database MongoDB on Ubuntu Linux through this in-depth ATA Learning tutorial!"
canonical: "https://adamtheautomator.com/mongodb-on-ubuntu-linux/"
---

# How to Install MongoDB on Ubuntu Linux

> Learn the ins-and-outs of installing NoSQL database MongoDB on Ubuntu Linux through this in-depth ATA Learning tutorial!

Source: https://adamtheautomator.com/mongodb-on-ubuntu-linux/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![How to Install MongoDB on Ubuntu Linux](https://adamtheautomator.com/wp-content/uploads/2023/05/install-mongodb-on-ubuntu.jpg)

# How to Install MongoDB on Ubuntu Linux

[![](https://secure.gravatar.com/avatar/2788bb1a3f735603f81eca51d68daec56a9d97e805a10268fb2c20afcc76b81b?s=192&d=mm&r=g)Nicholas Xuan Nguyen](https://adamtheautomator.com/author/nicholas-xuan-nguyen/)3 May 20237 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[MongoDB](/tag/mongodb/)[Ubuntu Linux](/tag/ubuntu-linux/)

Table of Contents

*   [Adding the Official MongoDB Repositories on Ubuntu Linux](#adding-the-official-mongodb-repositories-on-ubuntu-linux)
*   [Starting and Enabling the MongoDB Service](#starting-and-enabling-the-mongodb-service)
*   [Connecting to the Database Server and Creating a Dedicated User](#connecting-to-the-database-server-and-creating-a-dedicated-user)
*   [Enabling Authentication and Enforcing Access Control](#enabling-authentication-and-enforcing-access-control)
*   [Creating a New Database](#creating-a-new-database)
*   [Conclusion](#conclusion)

Are you tired of being constrained by the rigid structure of traditional relational databases? Look no further than MongoDB on Ubuntu Linux! With its document-oriented data model and ability to handle large amounts of data, MongoDB has become a popular choice for modern applications.

This tutorial will walk you through the step-by-step process of installing MongoDB on Ubuntu Linux, so you can confidently start building your next big project.

Read on and trust MongoDB to “Build faster. Build smarter”!

Prerequisites

This tutorial houses hands-on demonstrations. To follow along, ensure you have a machine running Ubuntu Linux. This tutorial uses Ubuntu 20.04, but the steps will also work on other versions.

Related:[How to Install Ubuntu 20.04 \[Step-by-Step\]](https://adamtheautomator.com/install-ubuntu/)

## Adding the Official MongoDB Repositories on Ubuntu Linux

Before taking advantage of MongoDB on Ubuntu Linux, you must add the required repositories, a set of software packages, and updates provided by MongoDB. These repositories include MongoDB’s latest stable release and any necessary dependencies.

Adding the MongoDB repositories allows you to quickly install and update MongoDB via the standard package management tools, like `apt`.

_**Related: [Learning Ubuntu Apt Get Through Examples](https://adamtheautomator.com/ubuntu-apt-get/)**_

To add the official MongoDB repositories, follow these steps:

1\. Open a terminal, and run the following `wget` command to download and add the MongoDB signing key to your Ubuntu machine’s trusted keyring. Doing so allows you to verify the integrity of the MongoDB packages you will install.

```bash
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
```

Related:[PowerShell wget : Awesome Way to Download a File](https://adamtheautomator.com/powershell-download-file/)

![Adding the MongoDB signing key](https://adamtheautomator.com/wp-content/uploads/2023/05/image-12.png)

Adding the MongoDB signing key

2\. Next, run the below [`apt-key`](https://www.thegeekdiary.com/apt-key-command-examples-in-linux/) command to verify that the signing key has been added.

This command displays a list of the keys added to your Ubuntu machine’s trusted keyring, including the MongoDB public key you added.

```bash
sudo apt-key list
```

![Verifying the added MongoDB public key](https://adamtheautomator.com/wp-content/uploads/2023/05/image-13.png)

Verifying the added MongoDB public key

3\. Run the `echo` command below to add the official MongoDB repositories to your Ubuntu machine’s package sources. Doing so allows you to download and install MongoDB.

```bash
echo "deb [ arch=amd64,arm64 ] <https://repo.mongodb.org/apt/ubuntu> focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
```

![Adding the official MongoDB repositories to the Ubuntu machine's package sources ](https://adamtheautomator.com/wp-content/uploads/2023/05/image-14.png)

Adding the official MongoDB repositories to the Ubuntu machine’s package sources

Related:[Echo Command in Bash Shell : Discover the Many Uses](https://adamtheautomator.com/echo-command-in-bash/)

4\. Once added, run the [`apt update`](https://linuxize.com/post/how-to-use-apt-command/#updating-package-index-apt-update) command below to update your package list. This command ensures you have access to the latest software packages and updates.

```bash
sudo apt update
```

![Updating the package list](https://adamtheautomator.com/wp-content/uploads/2023/05/image-15.png)

Updating the package list

5\. Now, run the below `apt-cache` command to verify that the MongoDB repositories have been added correctly and that your Ubuntu machine can find MongoDB packages.

```powershell
sudo apt-cache search mongodb
```

If all goes well, you will see an output like the one below.

![Verifying the MongoDB repositories have been added correctly](https://adamtheautomator.com/wp-content/uploads/2023/05/image-16.png)

Verifying the MongoDB repositories have been added correctly

6\. Finally, run the following `apt install` command to install MongoDB (`mongodb-org` package), which includes the MongoDB server, client, shell, and other tools on your Ubuntu Linux.

```bash
sudo apt install -y mongodb-org
```

![Installing MongoDB on Ubuntu Linux](https://adamtheautomator.com/wp-content/uploads/2023/05/image-17.png)

Installing MongoDB on Ubuntu Linux

## Starting and Enabling the MongoDB Service

At this point, you have successfully installed the MongoDB server. But right now, it is just quietly sitting there. Before you can use the MongoDB service, you first have to start and enable it

Run the below `systemctl` commands to `start` and `enable` the MongoDB service (`mongod`) to start on system boot time.

```bash
sudo systemctl start mongod
sudo systemctl enable mongod
```

Related:[Correct Way of Using Ubuntu systemctl to Control Systemd](https://adamtheautomator.com/ubuntu-systemctl/)

![Starting and enabling the MongoDB service to start at boot up](https://adamtheautomator.com/wp-content/uploads/2023/05/image-18.png)

Starting and enabling the MongoDB service to start at boot up

Now, run the command below to check the MongoDB service status.

```bash
sudo systemctl status mongod
```

Below, the output shows the MongoDB service has started and is running.

![Checking the MongoDB service status](https://adamtheautomator.com/wp-content/uploads/2023/05/image-19.png)

Checking the MongoDB service status

## Connecting to the Database Server and Creating a Dedicated User

With MongoDB on your Ubuntu Linux machine, it is time to test the database server. How? You will connect to the database server and create a dedicated user for your applications.

1\. Run the `mongosh` command below to connect to the database server, and opens the MongoDB shell, which allows you to interact with the database server.

Without arguments or options, the `mongosh` command connects to the MongoDB instance running on the default port of `27017` on the local system.

```bash
mongosh
```

As you can see below, you immediately connect to the database server without any authentication — yikes! This behavior comes with significant risks as it allows anyone accessing the server to read or modify data in your database.

To secure your MongoDB instance, you must create a dedicated user with appropriate roles and permissions (step two). This way, you can control who has access to the database and what actions they can perform.

![Connecting to the Database Server](https://adamtheautomator.com/wp-content/uploads/2023/05/image-20.png)

Connecting to the Database Server

2\. Next, run the following `use` command to switch to MongoDB’s `admin` database, the default database for administrative tasks.

```sql
use admin
```

![Switching to the admin database](https://adamtheautomator.com/wp-content/uploads/2023/05/image-21.png)

Switching to the admin database

3\. In the admin database, run the `db.createUser()` method below to create a new user with the username `MyDBAdmin` (which is arbitrary) and prompts you to enter a password.

The new user will be assigned the `userAdminAnyDatabase` and `readWriteAnyDatabase` roles. These roles allow users to create and manage users for any database and read from and write to any database.

```javascript
db.createUser(
    {
		// Set the new user's name
		user: "MyDBAdmin",
		// Prompts for the user password
		pwd: passwordPrompt(),
		// Set the roles for the new user
        roles: [
            { role: "userAdminAnyDatabase", db: "admin" },
            { role: "readWriteAnyDatabase", db: "admin" }
        ]
    }
)
```

When prompted, provide a secure password to create the new user in MongoDB. Save the password to a safe place; you will need it later to log in to the database server.

Related:[Secure Your Passwords with the Padloc Password Manager](https://adamtheautomator.com/padloc/)

![Creating a new user in MongoDB](https://adamtheautomator.com/wp-content/uploads/2023/05/image-22.png)

Creating a new user in MongoDB

4\. Now, run the below command to initiate a clean shutdown of the mongod instance to avoid data loss or corruption. Doing so ensures the database is closed correctly and all data is written to disk.

```bash
db.adminCommand( { shutdown: 1 } )
```

![Initiating a clean shutdown of the mongod instance](https://adamtheautomator.com/wp-content/uploads/2023/05/image-23.png)

Initiating a clean shutdown of the mongod instance

5\. Lastly, run the `exit` command to exit the MongoDB shell

```javascript
exit
```

![Exiting the MongoDB shell](https://adamtheautomator.com/wp-content/uploads/2023/05/image-24.png)

Exiting the MongoDB shell

## Enabling Authentication and Enforcing Access Control

Now that you already have a dedicated user with appropriate roles and permissions, you must secure each connection to the MongoDB server. You must enable authentication and enforce access control for all connections using a valid username and password.

To enable authentication and enforce access control:

1\. Open the _/etc/mongod.conf_ configuration file (the main configuration file for MongoDB) in your preferred text editor. This file is used to configure various settings for the mongod server process.

The mongod server process is the core component of MongoDB, responsible for the following:

*   Managing and accessing the database files on disk.
*   Handling client connections and requests.
*   Executing database operations.

```bash
sudo nano /etc/mongod.conf
```

Related:[Essential Tips for Installing & Using Sublime Text on Ubuntu](https://adamtheautomator.com/sublime-text-on-ubuntu/)

2\. Next, configure the following to enable authorization and enforce access control:

*   Locate the `security:` line in the file.
    
*   Remove the `#` character at the beginning to uncomment, and enable the `security:` line.
    
*   Add the `authorization: enabled` line below the `security:` line, as shown below.
    

Once configured, save the changes to the file, and exit the text editor.

![Enabling authentication and enforcing access control](https://adamtheautomator.com/wp-content/uploads/2023/05/image-25.png)

Enabling authentication and enforcing access control

3\. Now, run the following command to restart the `mongod` service to apply the changes.

This command does not produce output, but at this point, authentication and access control have been enabled in MongoDB. Users will now need to provide valid credentials to connect to the server.

```bash
sudo systemctl restart mongod
```

## Creating a New Database

With a secure server connection, you can now create a new database and insert entries. But first, you must ensure you are not overwriting any existing database.

To create a new database, follow these steps:

1\. Run the below commands to reconnect to the database server (`mongosh`) and switch to the `admin` database.

```bash
mongosh
use admin
```

![Connecting to the database server and switching to the admin database](https://adamtheautomator.com/wp-content/uploads/2023/05/image-26.png)

Connecting to the database server and switching to the admin database

2\. Next, run any command, like `show dbs`, to test if the authentication works.

```bash
show dbs
```

If the authentication and access control work, you will get an error message, as shown below, since you are not currently authenticated to perform any actions on the server.

![Testing if the authentication and access control work](https://adamtheautomator.com/wp-content/uploads/2023/05/image-27.png)

Testing if the authentication and access control work

3\. Run the below `db.auth()` method to authenticate your dedicated user (`MyDBAdmin`) and gain access to the server.

```javascript
db.auth("MyDBAdmin", passwordPrompt())
```

When prompted, provide the password you set for your dedicated user.

![Enter the password to authenticate the dedicated user](https://adamtheautomator.com/wp-content/uploads/2023/05/image-28.png)

Enter the password to authenticate the dedicated user

4\. Once authenticated, rerun the `show dbs` command to display a list of all databases your user can access on the server.

```javascript
show dbs
```

This time, the command pushes through without errors since you are now authenticated.

This example lists three databases: **admin**, **config**, and **local.**

![Displaying a list of all databases](https://adamtheautomator.com/wp-content/uploads/2023/05/image-29.png)

Displaying a list of all databases

5\. Now, run the below `use` command to create a new database called `my_db_demo` (arbitrary).

> _Unlike other traditional database systems, there is no separate command to create a new database in MongoDB. Instead, you can create a new database by simply switching to it by running the `use` command._

When you run the `use` command with a database name, MongoDB checks if the database already exists and switches to that database. Any subsequent commands you run will be executed in the context of that database.

But if the database does not exist, MongoDB creates a new one with the name you specified, switching to it as the active one.

```bash
use my_db_demo
```

![Creating and switching to a new database](https://adamtheautomator.com/wp-content/uploads/2023/05/image-30.png)

Creating and switching to a new database

6\. After creating a new database, run the following [`db.DB_NAME.insertOne`](https://www.mongodb.com/docs/manual/reference/method/db.collection.insertOne/) method (where `DB_NAME` is the database name) to insert a new document into your database.

The document contains two fields, `my_name`, and `my_age`, with the values `John Doe` and `40`, respectively.

```bash
db.my_db_demo.insertOne(
    {my_name: "John Doe",
    my_age: "40"
    }
)
```

![Inserting a new document into your database](https://adamtheautomator.com/wp-content/uploads/2023/05/image-31.png)

Inserting a new document into your database

7\. With a document inserted, run the below command to verify that your database (`my_db_demo`) has been created.

```javascript
show dbs
```

![Verifying that the new database has been created](https://adamtheautomator.com/wp-content/uploads/2023/05/image-32.png)

Verifying that the new database has been created

8\. Once verified, run the following [`db.DB_NAME.find()`](https://www.mongodb.com/docs/manual/reference/method/db.collection.find) method to retrieve the inserted data from your database.

```bash
db.my_db_demo.find( {} )
```

![ Retrieving the inserted data from your database](https://adamtheautomator.com/wp-content/uploads/2023/05/image-33.png)

Retrieving the inserted data from your database

## Conclusion

In this tutorial, you have learned how to set up MongoDB on Ubuntu Linux and secure it via the authentication and access control features. MongoDB is so powerful that it allows you to have a flexible database that can handle large amounts of data and scale with your growing needs.

Whether building a small project or a large-scale application, MongoDB is a great choice to help you achieve your goals. Why settle for less when you have MongoDB by your side? At this point, you can quickly start building your next big project with confidence.

With MongoDB, there are many advanced features and techniques you can explore. Not sure what to try next? Why not learn to deploy and manage MongoDB effectively with Docker?

Related:[How to Deploy and Manage a Docker MongoDB Container](https://adamtheautomator.com/docker-mongodb/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fmongodb-on-ubuntu-linux%2F&text=How%20to%20Install%20MongoDB%20on%20Ubuntu%20Linux)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fmongodb-on-ubuntu-linux%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fmongodb-on-ubuntu-linux%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2024/03/openldap-4.jpg)

### [How to Install and Configure an OpenLDAP Ubuntu Server](/openldap/)

Unlock the power of OpenLDAP on Ubuntu for centralized user authentication, seamless access control management, and enhanced directory services!

![](https://adamtheautomator.com/wp-content/uploads/2024/03/ubuntu-ntp.jpg)

### [How to Setup Ubuntu NTP Server](/ubuntu-ntp/)

Learn to configure an Ubuntu NTP server for precise time synchronization across your network. Ensure seamless operations with accurate timekeeping!

![](https://adamtheautomator.com/wp-content/uploads/2022/04/How-to-Install-Apache-on-Ubuntu.jpg)

### [Install Apache on Ubuntu and Master Website Traffic Management](/install-apache-on-ubuntu/)

Ready to optimize your website for high traffic? Install Apache on Ubuntu with this step-by-step guide and ensure smooth performance under heavy loads.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
