How to Install MongoDB on Ubuntu

Read it in 6 Mins

Last updated on
26th May, 2021
26th May, 2021
How to Install MongoDB on Ubuntu

MongoDB is an open-source document database used in numerous modern Web applications. MongoDB is also known as Mongo. It is classified as a NoSQL database because it does not have a traditional relational database structure based on the table.

Unlike relational databases, it uses dynamically based JSON-like documents, meaning that MongoDB requires no predetermined schema before you add data into it. You can change the structure anytime, without setting up a new database update structure.


  • Hardware Requirements:
    • RAM– 1 GB  
    • Storage- 256 GB of Hard Disk Space
  • Software Requirements:
    • Web Browser: Any browser such as Google Chrome, Mozilla Firefox, Microsoft Edge.
    • Operating System: An Ubuntu 18.04 server installed with a non-root sudo user and firewall.

Installation Procedure

Step 1 - Installing MongoDB

Ubuntu's package repositories contain the latest version of MongoDB.

You should include the dedicated MongoDB package repositories in APT sources in order to obtain the latest version of this software. Then you can install the mongodb-org, package which always indicates MongoDB's latest version.

1. Use the following command to load the public GPG key for the most recent version of MongoDB. In the URL section of the command, you should change 4.4 with the version you want to install if you intend to use a version of MongoDB other than 4.4:

curl -fsSL | sudo apt-key add -

You will get to see ok on the screen if the key was added successfully.

curl is a tool on the command line for numerous transmission systems. It reads any data stored on the URL to which it is transferred and shows the content on the output of the system. In this example, cURL displays the GPG key file contents and links it into the following sudo apt-key add - command, adding the GPG key to the keys list.

2. This curl command uses the -fsSL options that basically tell cURL to fail silently. That shows that if cURL does not contact the GPG server or the GPG server is down, the error code is not going to be added to the trusted keys list.

You can double-check whether the key has been added properly by:

$ apt-key list

You will get to see the key in the output like this:

Even now,the APT installation doesn’t know where you have to install the latest versions of MongoDB to locate the mongodb-org package.

You have two places on the APT Server where you can download and install online package sources: the sources.list file and the directory sources.list.d. The sources.list is a file listing the active APT data sources, with one source for each line. You can also add sources.list.d entries in separate files in the source.list directory.

3. Enter the following command, and create a file named mongodb-org-4.4.list in the sources.list.d directory:

$ echo "deb [ arch=amd64,arm64 ] bionic/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

4. Upgrade your local server package index to APT to know where to find the mongodb-org package after executing this command:

$ sudo apt update

5. Now, you can install MongoDB:

$ sudo apt install mongodb-org

Press Y and then ENTER to confirm that the package is to be installed.

MongoDB is installed on the system when the command is completed. It is not ready to be used, however. Next, you're going to run MongoDB and confirm it works.

Step 2 - Running the MongoDB Service

The previous step's installation configures MongoDB to run as a daemon maintained by the system, which means you can control MongoDB using different systemctl commands. However, the service will not start automatically with this installation process.

1. To start the MongoDB service, you can use the following command:

$ sudo systemctl start mongod.service

2. Check the status of the service at this point. Systemctl will automatically attach this to any argument passed if there aren't any already, so it is not important to include it:

$ sudo systemctl status mongod

This command returns this output, which indicates that the service is running:

3. Once the service is confirmed to run as expected, start the MongoDB service:

$ sudo systemctl enable mongod

4. The database can also be verified by connecting to the database and executing a diagnostic command. The following command will show its current version, server address and port. The response of the internal MongoDB connectionStatus command will also be returned:

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

ConnectionStatus checks back the database connection status and returns it. A value of 1 in the answer for the ok field shows that the server works as expected:


Note also that a loopback address of the locally located host is running at port 27017 on This is the default port number for MongoDB.

Next, we will examine how to manage the system instance of the MongoDB server.

Step 3 - Managing the Services

As already mentioned, mongoDB is set up as a system service for the installation process. This means that, as other Ubuntu system services, it can be managed with standard systemctl commands.

The systemctl status as previously mentioned, controls MongoDB service status:

$ sudo systemctl status mongod

To stop the service:

$ sudo systemctl stop mongod

To start the service when it is stopped:

$ sudo systemctl start mongod

To restart the server when it is running:

$ sudo systemctl restart mongod

Previously we have allowed MongoDB to start the server automatically. If this is required to be disabled, use:

$ sudo systemctl disable mongod

To re-activate the boot, execute the enable command again:

$ sudo systemctl enable mongod

Step 4 - Create MongoDB Database Root User and Password

1. MongoDB is deactivated by default, so it started off without access control. Run the following command to start the mongo shell.

$ mongo

2. You can list all available databases with the command below once you are connected to the mongo shell.

> show dbs

3. Switch first to the admin database and use the following commands to create the root user.

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

4. Without the --auth command line option the mongodb instance has been started. The authentication of users' needs must be enabled by editing the /lib/systemd/system/mongod.service file.

$ sudo nano /lib/systemd/system/mongod.service

5. See the ExecStart parameter under the [Service] config section and add --auth as a new option:

ExecStart=/usr/bin/mongod --auth --config /etc/mongod.conf

Now, save the service file and exit nano:

6. Reload the systemd services:

$ sudo systemctl daemon-reload

7. Now restart mongodb and try to connect it:

$ sudo service mongod restart

8. You must now authenticate yourself as a MongoDB user when you attempt to connect to mongodb. For instance:

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

Step 5 – Creating an example MongoDB database:

1. Create a demo database:

1. We will add some data into our demo database. You can use mongo shell to interact with MongoDB instance.  

Use the following command to open the mongo shell.

$ mongo

2. After opening MongoDB prompt, create a new database with the name demoDatabase using the following command:

$ use demoDatabase


Every piece of data in a MongoDB database should be part of a collection. But you don't have to explicitly create a collection. When using the insert method, the collection is automatically created.

3.Use the following command to add data into a collection:

$ db.myCollection.insert([
    {'name': 'Abhresh', 'age': 25},
   {'name': 'Ishan', 'age': 20},
    {'name': 'Nick', 'age': 30}

4. After successful insertion, you will get a message like this in the prompt:

Check the database size

Backups are great if you have large databases, and you need to check the size of your database before creating a backup in order to avoid running out of storage area and thus slowing or crashing your server.  

You can use the following commands to check the size:

$ db.stats().dataSize;


Create a Backup

You have to use the -d option to create a backup of a certain database and specify the database name. In addition, you should use the -o option and indicate a path to let mongodump know where to store the backup.

Exit from the mongo shell by using CTRL + D  

Use the following commands to create a backup:  

$ mongodump -d myDatabase -o ~/backups/first_backup

If the backup is successful, you will get this message:

Please note that backup creation is very expensive and can reduce the MongoDB instance performance.

We have successfully created a backup of MongoDB database and this shows that MongoDB is perfectly working on Ubuntu system.

Uninstall MongoDB from Ubuntu

To stop MongoDB first when it is currently being executed, remove MongoDB packages using the Advanced Package Tool, the library's MongoDB databases and the MongoDB log from the log directory.

Stop MongoDB Daemon Process

$ sudo service mongod stop

Remove Packages

$ sudo apt-get purge mongodb-org*

Remove MongoDB logs

$ sudo rm -r /var/log/mongodb

The above command will remove the logs and directories.

Remove Database

We will remove the MongoDB from the var/lib/mongodb. Please check if you have MongoDb in any other location, then change the MongoDB location in the command.

$ sudo rm -r /var/lib/mongodb

Learn more about the core concepts of MongoDB administration, indexes, security, Frameworks with MongoDB Admininstration Training


You added the official MongoDB repository to your APT instance and installed the latest version of MongoDB in this tutorial. You then practiced some systemctl commands and tested Mongo's functionality. This article also helped you to know how to create a backup of the MongoDB database.


Abhresh Sugandhi


Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of, which offers multiple services in technical training, project consulting, content development, etc.