How to Install MongoDB on Ubuntu 24.04

Introduction

MongoDB is a popular, open-source NoSQL database known for its high performance, high availability, and easy scalability. It stores data in JSON-like documents, making it a flexible and scalable choice for many developers and organizations. MongoDB is suitable for a variety of applications, from web development to big data projects and other data-intensive tasks. It provides a robust solution for your data management needs.

This guide shows you how to install MongoDB on Ubuntu 24.04

Prerequisites

Before you begin, ensure you've:

Install MongoDB

In this section, you will update your package index to ensure you have the latest information on the newest versions of packages and their dependencies.

  1. SSH to your Ubuntu server.
  2. Update the package information index.

    CONSOLE
    $ sudo apt update
    
  3. Download and install the MongoDB packages.

    CONSOLE
    $ sudo apt install -y mongodb
    
  4. Verify the installation by checking the MongoDB version.

    CONSOLE
    $ mongod --version
    

Manage MongoDB Service

In this section, you will manage the MongoDB service using systemctl.

  1. Start the MongoDB service.

    CONSOLE
    $ sudo systemctl start mongodb
    
  2. Enable MongoDB to start on boot.

    CONSOLE
    $ sudo systemctl enable mongodb
    
  3. Check the status of the MongoDB service.

    CONSOLE
    $ sudo systemctl status mongodb
    

Understand MongoDB Directory Structure

This section provides an overview of the MongoDB directory structure, including configuration, error, and log files.

  • MongoDB stores its data files in the /var/lib/mongodb directory.
  • Configuration files are located in the /etc/mongodb.conf file.
  • Log files are stored in the /var/log/mongodb directory.

Create Sample Database

In this section, you will create a sample database named company, set up a products collection, and insert sample documents into the collection.

  1. Open the MongoDB shell.

    CONSOLE
    $ mongo
    
  2. Create a sample company database .

    MQL
    use company
    
  3. Create a sample products collection.

    MQL
    db.createCollection("products")
    
  4. Insert sample documents into the products collection.

    MQL
    db.products.insertMany([
       { item: "laptop", qty: 50, price: 799 },
       { item: "phone", qty: 100, price: 599 },
       { item: "tablet", qty: 80, price: 399 }
    ])
    
  5. Query the products collection to retrieve the inserted documents.

    MQL
    db.products.find()
    

Conclusion

You have successfully installed MongoDB on Ubuntu 24.04 and created a sample database. You have also learned how to manage the MongoDB service, reviewed the directory structure, and inserted sample documents into a collection.

  • Databases
  • Webservers
  • PHP
  • API
  • Python
  • VPS Guides
  • Network
  • AI
  • Node.js