• January 3, 2026

How to Deploy MongoDB – NoSQL Document Database

How to Deploy MongoDB – NoSQL Document Database

Deploy MongoDB with Docker Compose on Ubuntu 24.04 for persistent log management and queries.

MongoDB is a document-oriented NoSQL database that stores data in flexible JSON-like documents. It provides high performance, automatic scaling, and rich query capabilities including aggregation pipelines and full-text search. MongoDB’s schema flexibility makes it well-suited for log management where log structures vary across services, and its indexing capabilities enable efficient querying of large log collections.

In this article, you will deploy MongoDB using Docker Compose and configure persistent storage for database files. You will access MongoDB through its shell to create databases, collections, and manage log documents.

Prerequisites

Before you begin, you need to:

  • Have access to an Ubuntu 24.04-based server as a non-root user with sudo privileges.
  • Install Docker and Docker Compose.

Set Up the Directory Structure and Environment Variables

In this section, you prepare the required directory structure for MongoDB and define environment variables in a .env file.

  1. Create the directory structure for MongoDB.
    console
    $ mkdir -p ~/mongodb-logging/mongodb-data

    This directory stores database files, collections, and indexes.

  2. Navigate into the mongodb-logging directory.
    console
    $ cd ~/mongodb-logging
  3. Create a .env file.
    console
    $ nano .env

    Add the following variables:

    ini
    MONGO_ROOT_USERNAME=admin
    MONGO_ROOT_PASSWORD=changeme

    Replace changeme with a strong password.

    Save and close the file.

Deploy with Docker Compose

In this section, you create and deploy the Docker Compose stack that runs MongoDB. Docker Compose manages the container and applies the environment variables from your .env file.

  1. Create a new Docker Compose manifest.
    console
    $ nano docker-compose.yaml
  2. Add the following content.
    yaml
    services:
      mongodb:
        image: mongo:latest
        container_name: mongodb
        hostname: mongodb
        ports:
          - "27017:27017"
        volumes:
          - "./mongodb-data:/data/db"
        environment:
          - MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USERNAME}
          - MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD}
        restart: unless-stopped

    Save and close the file.

    This manifest establishes:

    • services: One container providing database functionality:
      • mongodb: Executes the document-oriented database server and handles MongoDB wire protocol communications.
    • image: Latest MongoDB image sourced from Docker Hub’s official repository.
    • container_name: Static naming convention for predictable container identification.
    • hostname: Assigns the container’s network identifier used by clients and monitoring tools.
    • ports: Maps container port 27017 to the host system, enabling direct client connections.
    • volumes: Host directory (./mongodb-data) persists all database content including collections, indexes, and transaction logs.
    • environment: References administrative credentials from the .env file:
      • MONGO_INITDB_ROOT_USERNAME: Creates the root user account name for full database access.
      • MONGO_INITDB_ROOT_PASSWORD: Establishes the root user password.
    • restart: unless-stopped: Guarantees automatic container restart after crashes or host reboots, excluding manual stops.
  3. Create and start the service.
    console
    $ docker compose up -d
  4. Verify that the service is running.
    console
    $ docker compose ps

    Output:

    NAME      IMAGE         COMMAND                  SERVICE   CREATED          STATUS          PORTS
    mongodb   mongo:latest  "docker-entrypoint.s…"   mongodb   19 seconds ago   Up 18 seconds   0.0.0.0:27017->27017/tcp, [::]:27017->27017/tcp

    The container is operational. MongoDB accepts connections on port 27017.

  5. View container logs.
    console
    $ docker compose logs

    For more information on managing a Docker Compose stack, see the How To Use Docker Compose article.

Access MongoDB

This section guides you through testing your MongoDB installation via the mongosh shell, covering database creation, document insertion, and query execution for log management workflows.

  1. Access the MongoDB shell inside the container.
    console
    $ docker exec -it mongodb mongosh -u admin -p changeme

    Replace admin and changeme with your configured credentials from the .env file.

    Output:

    Current Mongosh Log ID: 692dcedbfb795baf399dc29c
    Connecting to:          mongodb://<credentials>@127.0.0.1:27017/?directConnection=true
    Using MongoDB:          8.2.2
    Using Mongosh:          2.5.9
    
    test>
  2. Switch to the logs database. MongoDB creates databases automatically when you first insert data.
    test> use logs

    Output:

    switched to db logs
  3. Insert a sample log document into the application_logs collection.
    logs> db.application_logs.insertOne({
            timestamp: new Date(),
            level: "INFO",
            message: "Application started successfully",
            service: "web-server",
            host: "app-01"
          })

    Output includes the inserted document ID:

    {
      acknowledged: true,
      insertedId: ObjectId('674893a1b2c3d4e5f6789012')
    }
  4. Query all log documents.
    logs> db.application_logs.find()

    Output displays your log entry:

    [
      {
        _id: ObjectId('674893a1b2c3d4e5f6789012'),
        timestamp: ISODate('2025-12-01T17:25:06.384Z'),
        level: 'INFO',
        message: 'Application started successfully',
        service: 'web-server',
        host: 'app-01'
      }
    ]
  5. Query logs with specific criteria.
    logs> db.application_logs.find({ level: "INFO" })
  6. Count total log documents.
    logs> db.application_logs.countDocuments()

    Output:

    1
  7. Insert multiple log entries at once.
    logs> db.application_logs.insertMany([
            {
              timestamp: new Date(),
              level: "ERROR",
              message: "Database connection failed",
              service: "api-server",
              host: "app-02"
            },
            {
              timestamp: new Date(),
              level: "WARN",
              message: "High memory usage detected",
              service: "worker",
              host: "app-03"
            }
          ])
  8. Query logs by severity level.
    logs> db.application_logs.find({ level: { $in: ["ERROR", "WARN"] } })
  9. Create an index on the timestamp field for improved query performance.
    logs> db.application_logs.createIndex({ timestamp: -1 })

    The -1 specifies descending order, optimizing queries that retrieve recent logs first.

  10. Show all collections in the current database.
    logs> show collections

    Output:

    application_logs
  11. Exit the MongoDB shell.
    logs> exit

Conclusion

You have successfully deployed MongoDB for log management with permanent data storage. The Docker-based deployment establishes a production-ready database instance where volume persistence guarantees data retention through container lifecycle events. MongoDB now accepts structured and unstructured log documents from application clients, executes sophisticated aggregation pipelines for log insights, and supports both vertical scaling through resource allocation and horizontal scaling via sharding as your logging infrastructure grows.

Leave a Reply

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