How to Create MongoDB Database and User on Ubuntu 20.04

How to create MongoDB database and User on Ubuntu 20.04. In this tutorial we will demonstrate how to install MongoDB on Ubuntu 20.04 and following that we will create a database and database user. Shall we start and introduce MongoDB first?

What is MongoDB ?

MongoDB is an opensource and highly popular NoSQL database used for building modern and scalable applications. It was founded in 2007 by a team of developers and is typically used in big data applications and other processes that do not align with traditional and rigid relational database models.

MongoDB is a distributed, high performance database that is ideal for developers working on highly available and high performance applications. It is popular for its horizontal scaling and load balancing which offers much needed scalability for running applications. In addition, it handles multiple data types including integers, strings, arrays, boolean, dates, and many more.

Unlike RDBMS ( Relational DataBase Management System) such as SQL, MongoDB is a schema less database and the concept of rows and columns is non existent. Instead of tables, data is stored in collections. A collection is a set of one or more documents where data is stored in JSON (JavaScript Object Notation) format. In this format, data is represented in key value format. The flexible document schemas make it possible to ingest unstructured data as well as add or delete data conveniently without affecting the collection.

MongoDB Features

MongoDB offers the following key features:


When data sits on a single database , it becomes prone to multiple risks such as hardware failure, or service interruptions. MongoDB offers database replication where data is copied from a central server to multiple servers for backup and disaster recovery. This translates to high availability of your data.


Indexing optimizes your database by improving the speed of query executions. In doing so, it improves the speed of data retrieval from a database table.  Failure to optimize query executions leads to a range of issues including delays in locating and accessing data.

MongoDB Sharding

Sharding is concept of breaking down large datasets into smaller and easily manageable parts called data shards. Sharding allows for greater horizontal scalability across independent servers each with their own computing resources. As a result, this allows for balancing of database operations with system resources.

MongoDB Load balancing

Thanks to features such as sharding and replication, MongoDB is able to support large scale load balancing. It is able to distribute millions of client requests across thousands of servers, and as a result, lead to better performance.

Adhoc queries for Mongo

MongoDB provides optimized ad-hoc query support for data that is updated in real time. This greatly improves read and write performance.

What can you do with MongoDB

A) Real Time Analytics.

B) Dynamicity and Scalability .

C) Product Catalogue.

At the time of publishing this guide, the latest version of MongoDB is 5.0. 

Why use Mongo DB?

MongoDB use cases

Key highlights include:

  1. Seamless data redistribution.
  2. No need for Virtual Machine to install the Database.
  3. Native time series features.
  4. Provides sharding, which is the process of storing the data in different machines.
  5. Can also be used as a file system.
  6. MongoDB can be run as windows service.
  7. Future proof application compatibility
  8. Serverless database on MongoDB Atlas.
  9. Multi Cloud security tools.
  10. Inclusion of Function Scoring feature in Atlas search for performing mathematical formulas within documents..

Benefits of MongoDB

MongoDB offers the following benefits:

Flexible document schemas

MongoDB, unlike relationaal databases like MySQL provide a flexible document schema that allows users to remodel and manipulate data at their convenience. As a result, it provides the much needed flexibility is storing data.

Robust querying and analytics

MongoDB server is designed to make access and retrieval of data fast and seamless. The MongoDB query API allows developers to perform complex queries with few lines of code.

MongoDB horizontal scaling with sharding

As a distributed database, MongoDB allows you to create multiple clusters with replication in real time and shard huge data sets across multiple servers. The end result is horizontal scaling which ensures maximum availability of data.

Availability of cloud based database solutions

MongoDB goes over and above what you would expect in a document database. It provides cloud offerings such as MongoDB Atlas for multi cloud deployments. It provides features such as automated data tiering, continuous backups, workload isolation and a host of security features.

High performance with MongoDB

Real time replication, optimized adhoc queries and sharding features contribute to the high performance of the database server. This is further improved by the flexible schema which is ideal in handling unstructured data.

Ease of installation

You can easily install MongoDB and set up clusters with a few commands. The same applies when deploying MongoDB Atlas which is a fully managed cloud database for managing complex deployments on cloud.

Extensive documentation and technical support

MongoDB provides thorough documentation for all their editions including Community, Enterprise and Atlas editions. If you are learning the ropes, or get stuck the support team will be there to offer solutions and guide you.

Below in this article you will find How to Create MongoDB Database and User on Ubuntu 20.04.

How to create MongoDB Database and User on Ubuntu 20.04

Read this guide to show you how you can create a MongoDB database and User on Ubuntu 20.04.  We will install the latest version from MongoDB repositories.


Before getting started with installing and creating a MongoDB database and user, ensure that you have the following in place.

  1. An instance of Ubuntu 20.04 server with SSH connection.
  2. A sudo or administrative user configured on the server.

With that out of the way, let us get started..

Step 1: Install MongoDB on Ubuntu 20.04

To get started, refresh the local package repositories as follows.

					$ sudo apt update

Next, install some prerequisite packages that will be required during the installation.

					$ sudo apt install software-properties-common gnupg apt-transport-https ca-certificates -y

The Ubuntu official repositories do not provide the latest version of MongoDB. As such, we will install from MongoDB repository. To do this, first, add the public GPG Key as follows.

					$ wget -qO - | sudo apt-key add -

This yields the output below.


Next, add the MongoDB 5.0 repository for Ubuntu 20.04 to the /etc/apt/sources.list.d directory as shown.

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


					deb [ arch=amd64,arm64 ] focal/mongodb-org/5.0 multiverse

Please update the local package repository to make your system aware of the newly added repository

					$ sudo apt update


With the repository added, you can now install the latest mongodb-org meta-package using the APT package manager as follows.

$ sudo apt install mongodb-org -y

When the installation is complete, you can verify the version of MongoDB installed as shown:

					$ mongod --version



					db version v5.0.9
Build Info: {
    "version": "5.0.9",
    "gitVersion": "6f7dae919422dcd7f4892c10ff20cdc721ad00e6",
    "openSSLVersion": "OpenSSL 1.1.1f  31 Mar 2020",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "ubuntu2004",
        "distarch": "x86_64",
        "target_arch": "x86_64"

The above output is a confirmation that MongoDB has successfully been installed

Step 2: Start and enable MongoDB

Typically, the MongoDB service does not automatically start upon installation. To confirm this, simply run the following command:

					$ sudo systemctl status mongod


					● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: inactive (dead)

From the above output, you can see that the MongoDB service is disabled, and hence not running. We, therefore need to go an extra step and enable the service.

To start the MongoDB service, run the following command:

					$ sudo systemctl start mongod

Additionally, be sure to enable the MongoDB service to automatically start on boot.

					$ sudo systemctl enable mongod



Created symlink /etc/systemd/system/ → /lib/systemd/system/mongod.service.


Step 3: Verify that the MongoDB service is running

Once you have started the MongoDB service, confirm that it is running by executing the following command:

$ sudo systemctl status mongod

This is the output:

					● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
     Active: active (running) since Fri 2022-06-17 12:28:15 UTC; 6min ago
   Main PID: 14582 (mongod)
     Memory: 63.0M
     CGroup: /system.slice/mongod.service
             └─14582 /usr/bin/mongod --config /etc/mongod.conf

Jun 17 12:28:15 ubuntu systemd[1]: Started MongoDB Database Server.

This time around, you can see that the service is running. Alternatively, you can verify that the database is running by initiating a connection to the MongoDB server using the following diagnostic command.

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


The command initiates a connection to MongoDB and displays information about the database server including the current version of MongoDB, the URL to the server, and the port it is listening on. Also, it returns the result of MongoDB’s internal connection Status command.


					MongoDB shell version v5.0.9
connecting to: mongodb://
Implicit session: session { "id" : UUID("25f5b361-0b28-431a-b9ce-4d937c44d463") }
MongoDB server version: 5.0.9
        "authInfo" : {
                "authenticatedUsers" : [ ],
                "authenticatedUserRoles" : [ ]
        "ok" : 1

The value 1 for the “ok” parameter indicates that the MongoDB database server is running as expected. The second line indicates the server URL and the port that the service it is listening on ( port 27017 ).

The Mongo server is installed now it is time to create a database in our guide how to Create MongoDB Database and User on Ubuntu 20.04.

Step 4: Create a database in MongoDB

So far, we have installed the MongoDB database server and ensured that it is running. Let us now shift gears and log and create a database and database user.

To log in, use the mongosh command-line tool as follows:

					$ mongosh

Once you run the command, you will drop to the MongoDB prompt. Above the prompt, you will details about MongoDB such as the version of the database server and the mongosh command-line tool.

Below that, you will get 2 warnings. The first one recommends you to use the XFS filesystem with WiredTiger Storage while the second one is an Access control warning indicating that you are restricted from reading and writing data on the database server. These warnings pop up because we haven’t created a user with password authentication yet. So don’t worry, the warnings will disappear once authentication to the database is enabled.

By default, MongoDB ships with three databases once installed. These are admin,config, and local. To display the existing databases, run the command.

					show dbs

Now, to create a new database, invoke the use command followed by the database name. For example, to create a database called cars run the command:

					use cars



Notice that the prompt now changes from test> to cars> .

switched to db cars


MongoDB prefixes the prompt with the current database name. This is particularly crucial when executing potentially critical commands as it notifies you of the database you are currently using.

You can verify that the database was created using the db command inside the database.



Here is the output:


To delete a database, use the db.dropDatabase() command. a litttle word of caution here. Be sure to switch to the directory that you want to delete before using this command. You can always confirm this using the db command as previously shown.


And the output:

					{ "dropped" : "cars", "ok" : 1 }

Step 5: Create an Administrative user in MongoDB

In this step, we will go further and create an administrative user in the database server. This user will have all the privileges on all the databases created in the database server.

Please create an administrative user with password authentication as follows. In this example, admin-user is the username.

    user: "admin-user",
    pwd: passwordPrompt(),
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]

Let us flesh out this command

The user:admin-user” line creates an administrative user, in this case, admin-user.

The pwd: passwordPrompt() method prompts you for the administrative user’s password. This is the recommended way of setting the user’s password instead of explicitly defining the password in clear text using the pwd: field.

MongoDB admin user

The roles: [ { role: “userAdminAnyDatabase”, db: “admin” }, “readWriteAnyDatabase” ] defines the roles granted to the admin user . The Admin user is granted read and write privileges to the admin database. With these permissions granted in the admin database, the administrative user, in effect, inherits the ability to read and make changes to all the databases in the database server.

Once executed, you will be prompted for the Admin user’s password.

Exit the Mongo Shell by running the exit command.


Step 6: Enable authentication for the Administrative user

After creating the Administrative user, you still need to go a step further and enable authentication. To accomplish this, you need to access and modify the MongoDB main configuration file which is /etc/mongod.conf

					$ sudo nano /etc/mongod.conf

Locate the ‘security‘ directive and uncomment it. Add the ‘authorization‘ parameter and set it to ‘enabled‘. Please note the indentation of the  authorization parameter.

					. . .
  authorization: enabled
. . . 

Save the changes and exit the configuration file. For the changes to come to effect, restart the MongoDB service.

					$ sudo systemctl restart mongod

It’s prudent to check if the service is running as expected.

					$ sudo systemctl status mongod

Now login to Mongo Shell.

					$ mongosh

This time around, you will observe that the warnings have disappeared.

To log in with authentication using the Administrative user, exit from the MongoDB shell and log in using the following syntax..

					$ mongosh -u admin-user -p --authenticationDatabase admin


 Authenticate with the password and hit ENTER.

That’s great! We have learned How to Create MongoDB Database and User on Ubuntu 20.04.

How to Create MongoDB Database and User on Ubuntu 20.04 Conclusion

In this guide, we have demonstrated how to install MongoDB on Ubuntu 20.04 and create a database and user as well. As a document database with a flexible schema, MongoDB comes out thw winner in handling unstructured when compared to relational databases such as MySQL and MariaDB. If you are developing applications that handled unstructured data, then MongoDB is a perfect database of choice. It’s fast, reliable and guarantees high avaialability and performance.

The demand for NoSQL databases like MongoDB has gone up in the recent times. Here are some real-world use cases of MongoDB along with some companies that use MongoDB for their practical applications. We hope this article will help you understand MongoDB and it’s practical applications.

This does it for this guide. It’s our hope that you can now comfortably create a database and database user in MongoDB. Check out MongoDB Atlas which is a fully-managed multi cloud database service.

Avatar for James Kiarie
James Kiarie

Hello everyone! My name is James, a certified Linux Administrator, and a tech enthusiast with over 5 years of experience in penning down high-quality guides on Linux and Cloud technologies. Outside work hours I enjoy working out, swimming, listening to music, and reading fiction novels.

5 2 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x