Introduction
MongoDB is a free and open source document database. It belongs to the NoSQL database family, which differs from traditional table-based SQL databases such as MySQL and PostgreSQL. Data in MongoDB is stored in flexible JSON-like documents where fields can vary from document to document. It does not require a predefined schema and the data structure can be changed over time.
Some key features of MongoDB are replication, indexing, user-defined searches, load balancing, and JavaScript execution.
This guide covers the step-by-step process of installing MongoDB on Ubuntu.
Prerequisites
To follow the installation steps, make sure you run the commands as root or a user with sudo privileges on an Ubuntu 22.04 or 20.04 instance.
Installing MongoDB on Ubuntu
Standard Ubuntu repositories usually include an outdated MongoDB version. We will install the official MongoDB packages, which are always up to date. Installing MongoDB on Ubuntu is quite simple. We will enable the MongoDB repository, import the repository's GPG key, and install the MongoDB packages.
As of this writing, the latest version of MongoDB available in the official MongoDB repositories is version 7.0.
The first step is to install the dependencies needed to add a new repository. These packages will most likely already be installed on your system, but some packages may be missing:
sudo apt update
sudo apt install gnupg wget apt-transport-https ca-certificates software-properties-common
Next, import the MongoDB repository GPG key to your system:
wget -qO- \
https://pgp.mongodb.com/server-7.0.asc | \
gpg --dearmor | \
sudo tee /usr/share/keyrings/mongodb-server-7.0.gpg >/dev/null
Add the MongoDB repository by creating the following file:
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] \
https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | \
sudo tee -a /etc/apt/sources.list.d/mongodb-org-7.0.list
The part in the $(lsb_release -cs)
command above prints the Ubuntu code name. For example, if you have Ubuntu version 22.04, the command will print grok
.
Once the repository is enabled, update the local package index:
sudo apt update
Now you can install MongoDB by typing:
sudo apt install mongodb-org
mongodb-org
is a metapackage that includes the following packages:
mongodb-org-server
- Themongod
daemon and corresponding initialization scripts and configurations.mongodb-org-mongos
- The demonmongos
e.mongodb-org-shell
- The mongo shell, an interactive JavaScript interface for MongoDB. It is used to perform administrative tasks via the command line.mongodb-org-tools
- Contains several MongoDB tools for importing and exporting data, statistics, and other utilities.
By default, the MongoDB daemon does not start after installation. To start the service and enable it at startup run:
sudo systemctl enable --now mongod
We can check whether the installation was successful by connecting to the MongoDB database server using the mongosh
shell tool and printing the connection status:
mongosh --eval 'db.runCommand({ connectionStatus: 1 })'
The output will look like this:
Current Mongosh Log ID: 655a70dfea9d876644ee6607
Connecting to: mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.0.2
Using MongoDB: 7.0.3
Using Mongosh: 2.0.2
{
authInfo: { authenticatedUsers: [], authenticatedUserRoles: [] },
ok: 1
}
The command returns information about the connection status, authenticated users and their permissions. A value of 1
for the ok
field indicates success.
MongoDB configuration
The MongoDB configuration file is located in the /etc
directory and is named mongod.conf
. The file uses the YAML format.
The default configuration settings are sufficient in most cases. However, for production environments, we recommend uncommenting the security section and enabling access control, as shown below:
sudo nano /etc/mongod.conf
security:
authorization: enabled
The authorization
option enables role-based access control (RBAC) that regulates user access to database resources and operations. If this option is not enabled every user will have access to all databases and perform any actions.
Every time you make configuration changes, you must restart the mongod service for the changes to take effect:
sudo systemctl restart mongod
To find more information about the configuration options available in the latest version of MongoDB, visit the Configuration File Options documentation page.
Creating the MongoDB administrative user
If you have enabled MongoDB authentication, you will need to create an administrative user who can access and manage your MongoDB instance.
Login to the mongo shell:
mongosh
From within the MongoDB shell, type the following command to connect to the admin
database:
use admin
switched to db admin
Run the following command to create an administrative user:
db.createUser(
{
user: "myMongoAdmin",
pwd: passwordPrompt(),
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
}
)
We called the administrator usage "myMongoAdmin". Feel free to call it whatever you like. You can also enter a plaintext password instead of the passwordPrompt()
method, but it is not recommended to display the password on the screen and it will also be saved in the shell history.
You will be prompted to type your password, type it and press "Enter." Don't forget to set a strong password:
Enter password
********{ ok: 1 }
"ok: 1" means the command was executed successfully.
Once done, exit the mongo shell with:
quit()
To test your changes, log in to the MongoDB shell using the administrative user you created earlier:
mongo -u myMongoAdmin -p --authenticationDatabase admin
You will be connected to the MogoDB shell if you enter the correct password.
Switch to the "admin" database and run show users
to get information about all users and their roles:
use admin
switched to db admin
show users
In our example, we have only one user:
[
{
_id: 'admin.myMongoAdmin',
userId: new UUID("a00ab5ca-5c1f-4a3b-8f67-be8a79c7649c"),
user: 'myMongoAdmin',
db: 'admin',
roles: [
{ role: 'userAdminAnyDatabase', db: 'admin' },
{ role: 'readWriteAnyDatabase', db: 'admin' }
],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}
]
Conclusion
We have shown you how to install and configure MongoDB on Ubuntu 20.04 and 22.04. For more information on this topic, visit the MongoDB Handbook.
If you encounter a problem or have feedback, please leave a comment below.