Install MongoDB on Ubuntu 18.04, 20.04, 22.04 & Debian

Posted on

Install MongoDB on Ubuntu 18.04, 20.04, 22.04 & Debian

Install MongoDB on Ubuntu 18.04, 20.04, 22.04 & Debian

MongoDB is a popular NoSQL database that is widely used for storing and managing large amounts of unstructured data. Its flexible schema and scalability make it a great choice for modern applications. In this guide, we will show you how to install MongoDB on Ubuntu 18.04, 20.04, and 22.04, ensuring you have a robust database solution ready for your projects.

Prerequisites

Before starting, you will need the following:

  • A running Ubuntu 18.04, 20.04, or 22.04 or Debian system.
  • A user account with sudo privileges.
  • An active internet connection.

Step 1: Add the MongoDB Repository

To install MongoDB, you will need to add the official MongoDB repository to your system’s package manager. This ensures you get the latest version and updates directly from MongoDB. You can do this by running the following command:

$ sudo apt-get install gnupg
$ wget -qO - https://www.mongodb.org/static/pgp/server-5.0.asc | sudo apt-key add -

The first command installs gnupg, which is required for verifying the integrity of the MongoDB packages. The second command downloads the MongoDB public key and adds it to your system’s trusted keys, allowing apt to verify the authenticity of the MongoDB repository.

Then you should create a new sources list file for MongoDB. This tells apt where to find the MongoDB packages. Choose the command that corresponds to your Ubuntu version:

Ubuntu 20.04:
$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list
Ubuntu 18.04:
$ echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/5.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-5.0.list

This command creates a new file /etc/apt/sources.list.d/mongodb-org-5.0.list containing the URL of the MongoDB repository for your specific Ubuntu version (focal for 20.04, bionic for 18.04). The tee command allows you to write the output of the echo command to both the file and the standard output. Ensure that your Ubuntu version matches the one specified in the command. There may be a more recent version of MongoDB available; you can check the MongoDB website for the latest repository configuration.

Step 2: Install MongoDB

Now that the repository is added, you can install MongoDB by running the following command:

$ sudo apt-get update
$ sudo apt-get install -y mongodb-org

The sudo apt-get update command refreshes the package lists, ensuring that your system is aware of the newly added MongoDB repository. The sudo apt-get install -y mongodb-org command then installs the MongoDB package along with all its dependencies. The -y flag automatically answers "yes" to any prompts during the installation process.

Step 3: Start MongoDB

After installation, you can start MongoDB by running the following command:

$ sudo systemctl start mongod

This command starts the mongod service, which is the core MongoDB server process.

You can also enable MongoDB to start automatically on boot:

$ sudo systemctl enable mongod

This command configures the system to automatically start the mongod service whenever the system boots up.

Verify that MongoDB is running by checking its status:

$ sudo systemctl status mongod

This command displays the current status of the mongod service, including whether it is running, its process ID, and any recent log messages. A successful installation will show that the service is active (running).

Conclusion:

With the successful installation and running of MongoDB on your Ubuntu 18.04, 20.04, or 22.04 system, you can now proceed with creating and managing your databases and collections.

Alternative Installation Methods

While the above method using the official MongoDB repository is generally recommended, here are two alternative approaches to installing MongoDB on Ubuntu:

1. Using Docker

Docker provides a containerization platform that allows you to run applications in isolated environments. This can be a convenient way to install MongoDB, as it avoids conflicts with other software on your system and provides a consistent environment across different platforms.

Explanation:

Using Docker, you don’t directly install MongoDB on your host machine. Instead, you download a pre-configured MongoDB image from Docker Hub and run it within a container. This container has everything MongoDB needs to run, including its dependencies. The benefits are isolation (no interference with other software), portability (easily move the container to different machines), and version control (easily switch between different MongoDB versions).

Steps:

  1. Install Docker: If you don’t have Docker installed, follow the official Docker documentation for Ubuntu: https://docs.docker.com/engine/install/ubuntu/

  2. Pull the MongoDB Docker Image:

    docker pull mongo

    This command downloads the latest MongoDB image from Docker Hub. You can also specify a specific version by using a tag, e.g., docker pull mongo:5.0.

  3. Run the MongoDB Container:

    docker run --name my-mongo -d -p 27017:27017 mongo
    • docker run: Creates and starts a new container.
    • --name my-mongo: Assigns the name "my-mongo" to the container.
    • -d: Runs the container in detached mode (in the background).
    • -p 27017:27017: Maps port 27017 on your host machine to port 27017 in the container. This allows you to connect to MongoDB from your host machine.
    • mongo: Specifies the image to use (the MongoDB image we pulled earlier).
  4. Connect to MongoDB:

    You can now connect to MongoDB using a MongoDB client (e.g., mongo shell) on your host machine.

    mongo

    This will connect to the MongoDB instance running in the Docker container. You may need to specify the host if it is not running on the same machine.

    mongo --host localhost

Code Example (Connecting with Python using pymongo):

from pymongo import MongoClient

client = MongoClient('localhost', 27017) # Replace with your Docker host if needed

db = client.testdb  # Connect to the 'testdb' database

# Insert a document
post = {"author": "John Doe",
        "text": "My first MongoDB document!",
        "tags": ["mongodb", "python", "pymongo"]}

posts = db.posts
post_id = posts.insert_one(post).inserted_id
print(f"Inserted post with ID: {post_id}")

# Find a document
retrieved_post = posts.find_one({"author": "John Doe"})
print(retrieved_post)

client.close() # Close the connection

This Python code connects to the MongoDB instance running in the Docker container on localhost, inserts a document, retrieves it, and then prints it to the console. You will need to install the pymongo library first: pip install pymongo.

2. Using a Cloud-Based MongoDB Service (MongoDB Atlas)

For production environments, or if you prefer not to manage the infrastructure yourself, using a cloud-based MongoDB service like MongoDB Atlas is a viable option.

Explanation:

MongoDB Atlas is a fully managed cloud database service provided by MongoDB. It takes care of all the underlying infrastructure, including server provisioning, backups, scaling, and security. You simply create an account, provision a cluster, and connect to it from your application. This simplifies deployment and management significantly, especially for larger applications.

Steps:

  1. Create a MongoDB Atlas Account: Go to https://www.mongodb.com/atlas/database and create a free account.

  2. Create a Cluster: Follow the instructions in the MongoDB Atlas interface to create a new cluster. You’ll need to choose a cloud provider (AWS, Azure, or GCP), a region, and a cluster size. MongoDB Atlas offers a free tier for small projects.

  3. Configure Network Access: Configure the network access to allow your application to connect to the cluster. You’ll need to whitelist your IP address or allow access from all IP addresses (not recommended for production).

  4. Create a Database User: Create a database user with appropriate permissions to access the database.

  5. Get the Connection String: MongoDB Atlas provides a connection string that you can use to connect to the cluster from your application. The connection string will look something like this:

    mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<database-name>?retryWrites=true&w=majority

    Replace <username>, <password>, <cluster-name>, and <database-name> with your actual credentials and cluster name.

Code Example (Connecting with Python using pymongo):

from pymongo import MongoClient

# Replace with your MongoDB Atlas connection string
connection_string = "mongodb+srv://<username>:<password>@<cluster-name>.mongodb.net/<database-name>?retryWrites=true&w=majority"

client = MongoClient(connection_string)

db = client.testdb  # Connect to the 'testdb' database

# Insert a document
post = {"author": "Jane Smith",
        "text": "Using MongoDB Atlas is easy!",
        "tags": ["mongodb", "python", "atlas"]}

posts = db.posts
post_id = posts.insert_one(post).inserted_id
print(f"Inserted post with ID: {post_id}")

# Find a document
retrieved_post = posts.find_one({"author": "Jane Smith"})
print(retrieved_post)

client.close() # Close the connection

This Python code connects to your MongoDB Atlas cluster using the connection string, inserts a document, retrieves it, and then prints it to the console. Remember to replace the placeholder connection string with your actual connection string from MongoDB Atlas.

These alternative methods offer different trade-offs in terms of complexity, control, and cost. Choosing the right method depends on your specific needs and requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *