MongoDB Lab Series: Environment Setup

Tutorial 01

Complete Environment Setup

We need to prepare the environment to properly execute MongoDB. This involves installing Docker, deploying a MongoDB 8 container, and setting up the mongosh CLI — all driven from the command line.

Select Your Linux OS:
Toggles commands dynamically across steps
1

Install Docker Engine

What is Docker? Docker packages applications and dependencies into standardized containers, ensuring absolute environment consistency regardless of host system configuration.

Terminal — Ubuntu / Debian Setup bash
# Update package list and install prerequisites
sudo apt update
sudo apt install -y apt-transport-https ca-certificates curl software-properties-common

# Add Docker's official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Add Docker repository
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker Engine & Compose plugin
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io

# Add user to docker group (removes sudo requirement)
sudo usermod -aG docker $USER
newgrp docker

# Verify installation
docker --version
Post-Installation Verification Test
# Test Docker daemon with hello-world container
docker run hello-world
Expected Output: Should display message starting with "Hello from Docker!"
Important: Activate the Docker Group

After adding your user to the docker group, log out and log back in (or restart your computer) so the change takes effect. Then verify:

# Confirm the docker group is active in your session
groups

# Test Docker daemon access without sudo
docker ps
2

Setup MongoDB Container

We will deploy MongoDB using Docker Compose. This provides a clean, reproducible database service running in an isolated environment.

1. Initialize Project & Configuration File

# Create and navigate to project directory
mkdir mongodb-tutorial
cd mongodb-tutorial

# Create the orchestration file
nano docker-compose.yml
Nano Editor Keyboard Commands:
  • Paste content: Right-click inside the nano window and select Paste, or press Ctrl+Shift+V (or Shift+Insert).
  • Save the file: Press Ctrl+O (Write Out), press Enter to confirm the filename.
  • Exit nano: Press Ctrl+X. If asked to save changes, press Y then Enter.
Contents for docker-compose.yml:
services:
  mongodb:
    image: mongo:7
    container_name: mongodb
    restart: unless-stopped
    ports:
      - "27017:27017"
    environment:
      MONGO_INITDB_ROOT_USERNAME: admin
      MONGO_INITDB_ROOT_PASSWORD: password
    volumes:
      - mongo_data:/data/db

volumes:
  mongo_data:
Directive Description
image: mongo:7 Pulls the official MongoDB v7 stable production image
ports: "27017:27017" Maps local host port 27017 to the container port
environment Initializes root admin credentials (admin/password)
volumes Attaches named volume mongo_data for data persistence

2. Launch Service

# Start container in detached mode
docker compose up -d

# Verify container running state
docker ps
3

Setup MongoDB Shell (mongosh)

What is mongosh? mongosh is the modern MongoDB interactive shell used to inspect, query, and administrative database entities.

Access and Ping MongoDB Instance:
# Connect directly into container shell
docker exec -it mongodb mongosh

# Run ping command inside mongosh
db.runCommand({ ping: 1 })
If you see { ok: 1 } as the output, MongoDB is correctly connected and running.
Authenticate Admin Credentials:
// Switch to admin database context
use admin

// Authenticate with configured credentials
db.auth("admin", "password")

// Exit shell session when complete
exit
4

Import Sample Supplies Dataset

We will import the standard production-grade Sample Supplies dataset containing 28,000+ sales records to populate our database for analysis.

1. Download and Transfer Raw JSON Dataset:
# Create local data directory
mkdir data && cd data

# Download JSON dataset
curl -O https://raw.githubusercontent.com/neelabalan/mongodb-sample-dataset/refs/heads/main/sample_supplies/sales.json

# Copy dataset into running MongoDB container
docker cp sales.json mongodb:/tmp/sales.json
2. Execute Import Tool (mongoimport):
docker exec -i mongodb mongoimport \
  --db sample_supplies \
  --collection sales \
  --file /tmp/sales.json \
  --username admin \
  --password password \
  --authenticationDatabase admin
3. Verify Record Insertion Count:
docker exec -it mongodb mongosh -u admin -p password --authenticationDatabase admin --eval "db.getSiblingDB('sample_supplies').sales.countDocuments()"
Expected Count Result: 5000 documents imported successfully.
Understanding the Command — Part by Part
Command Part What It Does
docker exec -it mongodb Runs a command inside the running mongodb container (-it keeps the terminal interactive)
mongosh Launches the MongoDB Shell inside the container
-u admin Specifies the database username as admin
-p password Specifies the password for that user
--authenticationDatabase admin Tells mongosh which database stores the user credentials — here, admin. Without this flag the shell cannot log in and the count will not show.
--eval "..." Runs the quoted script non-interactively and prints its result, instead of opening an interactive prompt
db.getSiblingDB('sample_supplies') Switches to the sample_supplies database and returns it as a db object — a reliable way to target a database in a one-line script
.sales Selects the sales collection inside that database
.countDocuments() Counts every document in the collection and returns the total number

Tutorial Verification Checklist

Run these automated integrity checks to ensure environment readiness before proceeding.

1. Docker Daemon docker ps

Lists active active containers

2. Container Health Ping docker exec -it mongodb mongosh --eval "db.runCommand({ ping: 1 })"

Returns { ok: 1 }

3. Dataset Integrity docker exec -it mongodb mongosh -u admin -p password --authenticationDatabase admin --eval "db.getSiblingDB('sample_supplies').sales.countDocuments()"

Returns 28554 count

Troubleshooting Common Issues

Quick Reference Commands

Bookmark these everyday utility CLI triggers for future lab assignments.

# Start MongoDB service
docker compose up -d

# Terminate MongoDB service
docker compose down

# Monitor container health
docker ps

# Shell connection access
docker exec -it mongodb mongosh

# List all database namespaces
docker exec -it mongodb mongosh --eval "show dbs" -u admin -p password --authenticationDatabase admin

# Evaluate sales dataset total document count
docker exec -it mongodb mongosh -u admin -p password --authenticationDatabase admin --eval "db.getSiblingDB('sample_supplies').sales.countDocuments()"