Are you looking to learn how to install MongoDB on Ubuntu 22.04 VPS or a dedicated server? This guide will walk you through the MongoDB installation process step-by-step!
MongoDB is favored by developers for its flexibility, scalability, performance, and robust ecosystem—essential features for building modern applications. With just a few configuration steps, you can set up MongoDB on Ubuntu 22.04 LTS, the latest long-term support version of the Ubuntu Linux distribution.
Setting up and configuring MongoDB community server on Ubuntu 22.04 is straightforward, but a few steps can be tricky for beginners. That’s why we’ve put together this easy-to-follow tutorial. By the end, you’ll learn how to install MongoDB on Ubuntu 22.04 with minimal hassle.
PREREQUISITES
Before getting started, make sure you have the following:
- Ubuntu 22.04 server should be installed on your machine.
- You should have root or sudo privileges to run administrative commands.
- A properly configured firewall to secure your server
WHAT IS MONGODB?
MongoDB is a high-performance NoSQL database designed for document-based data storage. It’s open-source and available under the GNU Affero General Public License (GPL), making it a popular choice for modern web applications.
Built with features like horizontal scaling, geographic distribution, and high availability, it functions as a powerful distributed database right out of the box. Developed in C++, MongoDB stores data in BSON (Binary JSON) format, which allows flexible, JSON-like documents.
MongoDB's flexible document model, dynamic schemas, and built-in scalability make it a popular choice for agile development, as it imposes fewer constraints on how data is structured and managed. This means each document can have a different structure, and fields can be added or modified as needed over time.
MongoDB only provides specialized packages for 64-bit Long-Term Support (LTS) versions of Ubuntu. Supported releases include Ubuntu 22.04 (Jammy Jellyfish), and 20.04 (Focal Fossa).
WHAT ARE THE USES OF MONGODB IN MODERN DEVELOPMENT?
MongoDB is ideal for developing applications, including web and mobile apps, that handle large volumes of rapidly changing, semi-structured, or unstructured data. Its flexible data model makes it an excellent choice for developers looking to quickly create scalable applications capable of managing extensive data processing needs.
The current stable version is MongoDB 7.0, released in August 2013. This major release supports both on-premise installations and MongoDB Atlas, which is a multi-cloud database service.
MongoDB 7.0 introduces several key enhancements to improve the developer experience:
- Enhanced Security: Features like Queryable Encryption allow for client-side data encryption while enabling expressive queries on randomized data.
- Performance Improvements: New functionalities include compound wildcard indexing and better sharding diagnostics at the metadata, cluster, database, and collection levels. Additionally, working with time-series data and large datasets has been optimized.
- Efficient Data Migration: The cluster-to-cluster synchronization feature offers greater flexibility for syncing data across different database clusters.
- Improved Developer Experience: Enhancements include user role variables, support for fine-grained updates and deletions in time-series collections, better cache refresh times, and much more.
For a detailed overview of the latest features and improvements in MongoDB 7.0, refer to the release notes.
HOW TO INSTALL MONGODB ON UBUNTU 22.04? (INSTALLING MONGODB ON UBUNTU)
To learn how to install MongoDB on Ubuntu 22.04 system, follow the below steps:
STEP 1: INSTALL REQUIRED PACKAGES
Before starting the MongoDB installation on Ubuntu, you first need to install the required dependencies or packages that are necessary to run MongoDB on your system. You can install these packages by using this command:
$ sudo apt update
$ sudo apt install software-properties-common gnupg apt-transport-https ca-certificates -y
STEP 2: IMPORT MONGODB PUBLIC GPG KEY
To install the latest version of MongoDB, you’ll first need to add its package repository to your Ubuntu sources list. Before doing that, you must import MongoDB’s public key into your system using the following curl or wget command:
$ curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
STEP 3: ADD MONGODB REPOSITORY TO THE SOURCE LIST
In this step, you will add the MongoDB 7.0 APT repository to the /etc/apt/sources.list.d directory.
$ echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
This command creates a sources list file for MongoDB 7.0 in the /etc/apt/sources.list.d/ directory. The file contains a single line that reads:
$ echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse"
STEP 4: UPDATE PACKAGES REPOSITORY
At this point, the MongoDB 7.0 repository has been added. The next step is to update Ubuntu so it can recognize the packages from the new repository. Use the following command to refresh the package list:
$ sudo apt-get update
With that, your system is ready for the MongoDB installation.
STEP 5: INSTALL MONGODB ON UBUNTU 22.04 (INSTALLING MONGODB)
Now, execute the following command to install MongoDB on Ubuntu 22.04 from the repository:
$ sudo apt-get install -y mongodb-org
The above command installs the MongoDB database server along with its core components, including the shell tools.
STEP 6: CHECK MONGODB VERSION
After the installation finishes, you can check the installed version of MongoDB:
$ mongo --version
This command provides various details, including the version of MongoDB, along with information about Git and OpenSSL versions, among other specifics.
MONGODB SERVICE MANAGEMENT
By default, the MongoDB service is disabled after installation, which you can check by running the following command:
$ sudo systemctl status mongod
To start the MongoDB service, use this command:
START MONGODB SERVICE
$ sudo systemctl start mongod
You can verify that the service is running again with:
CHECK MONGODB SERVICE STATUS
$ sudo systemctl status mongod
If everything is working correctly, you will see that MongoDB is active. Additionally, you can confirm the database is operational by checking if the server is listening on its default port, 27017. To do this, run:
$ sudo ss -pnltu | grep 27017
You should see the appropriate output in your terminal indicating active ports for MongoDB.
Once you've confirmed that the service is running properly, you can enable MongoDB to start automatically on boot with the following command:
ENABLE MONGOD SERVICE
$ sudo systemctl enable mongod
At this point, MongoDB has been successfully installed and configured to start on system startup.
CONFIGURING MONGODB USERS/PASSWORDS
At this point, your MongoDB instance should be up and running, and configured for remote access. Now, let’s move on to creating a database and a user within MongoDB.
To access MongoDB, execute the command:
$ mongosh
Before entering the MongoDB shell, you will see some introductory details, including the MongoDB version and the Mongosh documentation URL.
You will also notice a warning at the top of the shell prompt indicating that access control has not yet been enabled. This warning means that read and write access to the database and its configuration is unrestricted. It will disappear once authentication is activated.
By default, three databases are created during installation: admin, config, and local. To view the existing databases, use the command:
> show dbs
To create a new database, use the use command followed by the desired database name. For example, to create a database named employees, run:
> use employees
To confirm the database you are currently in, use the following command, which will return employees:
> db
MongoDB offers various shell methods for database management. You can create a new user in a database with the db.createUser method. This requires specifying the username, password, and any roles you want to assign to the user, presented in JSON format.
Here’s how to create a user named test user with read and write roles on the employee's database:
db.createUser(
{
user: "test",
pwd: "some_password",
roles: [{ role: "readWrite", db: "employeesdb" }]
}
)
To see a list of users you’ve created, use the db.getUsers() method:
db.getUsers();
Alternatively, you can check users with:
> show users
If you need to delete a user, you can do so using the db.dropUser method:
db.dropUser("test", { w: "majority", wtimeout: 4000 })
HOW TO ENABLE AUTHENTICATION ON MONGODB SERVER ON UBUNTU?
By default, MongoDB does not enable authentication, which means that anyone with access to the database server can read, add, or remove data. This lack of security can pose significant risks to your data integrity. In this section, we will walk you through the process of securing MongoDB on Ubuntu 22.04.
CREATING AN ADMINISTRATIVE USER
Start by accessing the MongoDB shell:
$ mongosh
Next, switch to the admin database:
> use admin
Now, you can create an administrative user by executing the following command:
db.createUser(
{
user: "AdminTest",
pwd: passwordPrompt(),
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
Let’s break down this command:
user: "AdminTest": This line creates an administrative user named AdminTest.
pwd: passwordPrompt(): This method prompts you for the password for the administrative user, providing a more secure option than directly typing the password in plain text.
roles: The specified roles grant the user administrative permissions across the cluster. In this case, the user is given read-and-write access to the admin database and, consequently, can modify all databases within the cluster.
Once you run the command, you will see the output confirming the user creation.
To exit the MongoDB shell, use the exit command or press CTRL + C.
ENABLE AUTHENTICATION
With the administrative user created, the next step is to enable authentication. To do this, first exit the MongoDB shell and open the configuration file:
$ sudo nano /etc/mongod.conf
Locate the security section in the file. Uncomment it, add the authorization directive, and set it to enabled:
security:
authorization: enabled
Make sure that the authorization parameter is indented correctly, while the security line does not have leading spaces.
After saving your changes and closing the configuration file, restart the MongoDB service to apply the modifications:
$ sudo systemctl restart mongod
Then, verify that the service is running correctly:
$ sudo systemctl status mongod
Next, log back into the MongoDB shell:
$ mongosh
You should notice that the startup warnings have been resolved. However, if you try to execute any database commands, like listing the databases, you will be prompted that authentication is required:
> show dbs
AUTHENTICATING THE USER
To authenticate, first log out of the MongoDB shell by using the exit command. Then log back in using the administrative user:
$ mongosh -u AdminTest -p --authenticationDatabase admin
After entering the password for the administrative user, the previous authentication warnings should no longer appear.
From this point onward, only the administrative user will have the ability to view, create, and modify data within the database. To exit the MongoDB shell, simply run the exit command again. That is it!
HOW TO CONFIGURE MONGODB FOR REMOTE ACCESS?
By default, MongoDB is configured to allow local access only, meaning it can only be accessed from the server where it’s installed. To enable remote access, you need to modify the /etc/mongod.conf configuration file.
Open the Configuration File: Use a text editor to open the MongoDB configuration file:
sudo nano /etc/mongod.conf
Modify Network Interfaces: Find the network interfaces section, which looks like this:
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1
By default, bindIp is set to 127.0.0.1, allowing only local connections. To permit remote access, add your MongoDB server's IP address, separated by a comma:
bindIp: 127.0.0.1, mongo-server-ip
Save Changes and Restart: After making these changes, save the file and exit the editor. Then, restart MongoDB to apply the new settings:
$ sudo systemctl restart mongod
Configure Firewall: If UFW is enabled, allow incoming connections on port 27017 from the remote machine:
$ sudo ufw allow from remote_machine_ip to any port 27017
Reload the firewall to apply the changes:
$ sudo ufw reload
ACCESSING MONGODB REMOTELY
You can access MongoDB remotely using a couple of methods:
Using Netcat: If Netcat is not installed on the client machine, install it:
sudo apt install netcat
Then, establish a TCP connection to the MongoDB server:
nc -zv mongodb_server_ip 27017
A successful connection will display:
Connection to mongodb_server_ip 27017 port [tcp/*] succeeded!
Using Mongo Shell: You can also log in directly using the Mongo Shell with the following command:
mongosh "mongodb://username@mongo_server_ip:27017"
You will be prompted for the admin user’s password.
HOW TO WORK WITH MONGODB DATABASE? (BASIC CRUD OPERATIONS)
MongoDB enables various database operations, including creating, retrieving, updating, and deleting records.
1. INSERTING DATA IN MONGODB
To add a document to a collection, use the .insertOne() method. For example, login and switch to the “employeesdb” database:
mongosh -u AdminTest -p --authenticationDatabase admin
use employeesdb
Then create a collection named office and insert a document:
db.office.insertOne({ name: "jhon", age: 21, city: "new york", married: true, hobbies: [ "Swimming", "Cooking"] })
2. RETRIEVING DATA FROM MONGODB
Retrieve documents using the .find() method. To get all documents in the staff collection:
db.office.find()
You can add more documents and filter results. For instance, to find married employees:
db.office.find({ married: true })
3. UPDATING DATA IN MONGODB DATABASE
To modify a document, use the .update() method. For example, change Bob's name to Robert:
db.office.update({ name: "canny" }, { $set: { name: "harry" } })
Verify the update:
db.office.find({ name: "harry" })
4. DELETING DATA FROM MONGODB
Use .deleteOne() to remove a single record, preferably using the unique _id:
db.office.deleteOne({ _id: ObjectId("64f7a050a974192c06cdcea0") })
To delete multiple documents, use .deleteMany(). For example, to remove all married employees:
db.office.deleteMany({ married: true })
To clear all documents from the collection, execute:
db.office.deleteMany({})
Afterward, querying the collection will return no results, indicating it is empty:
db.office.find()
CONCLUSION
In this tutorial, you successfully added the official MongoDB repository to your APT instance and how to install MongoDB on Ubuntu 22.04. You also tested MongoDB's functionality and practiced using some systemctl commands.
As a next step, we highly recommend securing your MongoDB installation by following our guide on How to enable secure authentication MongoDB on Ubuntu 20.04. Once you have secured your setup, you can proceed to configure MongoDB for remote connections.
For additional tutorials on configuring and utilizing MongoDB, explore the MongoDB installation manuals and community articles. We also encourage you to visit the official MongoDB documentation, which serves as an excellent resource for exploring MongoDB’s capabilities.
Are you looking for Reliable VPS Hosting, Dedicated Servers, or SSL Services?
Host World offers top-tier solutions across 17 countries, ensuring global availability and uninterrupted business operations.
Why Choose Us?
- Fast Support: 10-minute response time, minimizing downtime and losses.
- 24/7 Multilingual Support: For seamless communication and assistance.
- 99.9% Uptime: Reliable performance to keep your business online.
- Affordable Pricing: Plans tailored to various locations to suit your budget.
Get the best hosting and server solutions with Host World, backed by premium service and global reach!
Don’t miss out on the opportunity to enhance your hosting experience—order your VPS server today and unlock the potential of powerful, flexible hosting!