Comprehensive Guide to Installation and Configuration of MongoDB

by | MongoDB

Introduction to MongoDB

Overview

MongoDB is a popular NoSQL database system that uses a document-oriented data model. It’s designed for scalability, flexibility, and ease of development. This guide provides a practical approach to installing and configuring MongoDB on various operating systems including Windows, macOS, and Linux.

Installation

Windows Installation

Download MongoDB:

Select the latest MongoDB version and ensure the package is for Windows.

Install MongoDB:

Run the downloaded .msi file.
Follow the installation prompts and select “Complete” setup type.
During the installation, ensure you check the “Install MongoDB as a Service” option.

Setup Environment Variables:

Add the MongoDB bin directory to your system’s PATH environment variable:
C:Program FilesMongoDBServer<version>bin

Start MongoDB:

MongoDB should have been installed as a service and started automatically. You can verify it by checking services or using the command prompt:
net start MongoDB

macOS Installation

Install via Homebrew:

Open Terminal.
Install Homebrew if it’s not already installed:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Install MongoDB:
brew tap mongodb/brew
brew install mongodb-community

Start MongoDB:

Use Homebrew services to start MongoDB:
brew services start mongodb/brew/mongodb-community

Linux Installation (Ubuntu as an example)

Import the public key used by the package management system:

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

Create a list file for MongoDB:

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

Reload local package database:

sudo apt-get update

Install MongoDB packages:

sudo apt-get install -y mongodb-org

Start MongoDB:

sudo systemctl start mongod

Enable MongoDB to start on boot:

sudo systemctl enable mongod

Configuration

Configuration File (mongod.conf)

Location:

The default location for the configuration file is:
Windows: C:Program FilesMongoDBServer<version>binmongod.cfg
macOS and Linux: /etc/mongod.conf

Editing the Configuration:

Use a text editor to edit mongod.conf. Below is an example configuration:
# mongod.conf

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

# Where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

# Process Management Options
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

Apply Configuration Changes:

Restart MongoDB services for changes to take effect:
Windows:
net stop MongoDB
net start MongoDB
macOS and Linux:
sudo systemctl restart mongod

Verification

Verify MongoDB is running:

You can check if MongoDB is running by connecting to the MongoDB shell.
mongo
This opens the MongoDB shell and connects to the running MongoDB instance.

Check MongoDB status:

On Windows:
net start MongoDB
On macOS and Linux:
sudo systemctl status mongod

By following these detailed instructions, you will have MongoDB installed and configured on your operating system, ready for development and educational purposes.

Preparing Your Environment

In this section, we will cover preparing your system to work effectively with MongoDB after installation. This includes starting and stopping the MongoDB service, connecting to the MongoDB server, and creating a basic database and collection.

Starting and Stopping the MongoDB Service

On Windows

Starting MongoDB:

net start MongoDB

Stopping MongoDB:

net stop MongoDB

On macOS

Starting MongoDB using Homebrew:

brew services start mongodb/brew/mongodb-community

Stopping MongoDB:

brew services stop mongodb/brew/mongodb-community

On Linux (systemd)

Starting MongoDB:

sudo systemctl start mongod

Stopping MongoDB:

sudo systemctl stop mongod

Connecting to MongoDB Server

After starting the MongoDB service, you can connect to the MongoDB server using the mongo shell.

Mongo Shell Command

mongo

Executing the above command in your terminal will start the MongoDB shell and connect to the default mongod instance running on localhost at port 27017.

Creating a Basic Database and Collection

Once connected to the MongoDB shell, you can create a database and a collection.

Create a Database

use myNewDatabase

The use command switches your context to myNewDatabase. If myNewDatabase does not exist, it will be created when you insert some data into it.

Create a Collection

db.createCollection("myNewCollection")

This command will create a collection named myNewCollection within the myNewDatabase.

Insert Data into Collection

db.myNewCollection.insertOne({ name: "MongoDB", type: "Database", year: 2009 })

This command inserts a single document into myNewCollection.

Verification

To verify that your database and collection have been created, you can use the following commands:

Show Databases

show dbs

Show Collections in the Current Database

show collections

Query the Collection

db.myNewCollection.find().pretty()

This will display the documents in a readable format.

Use these steps to ensure that your MongoDB environment is correctly prepared and that you can interact with the database as intended.

Part 3: Installing MongoDB on Windows

This section will provide a practical guide for installing MongoDB on a Windows operating system. Before starting, ensure that you have administrative access on your Windows machine.

Step-by-Step Installation Guide

1. Download MongoDB

Choose the version you want and select Windows as your operating system.
Click “Download” to get the .msi installer file.

2. Run the .msi Installer

Locate the downloaded .msi file and double-click to run it.
Follow the installation wizard steps:
Accept the license agreement.
For Setup Type, choose Complete.

3. Configure the Installation

In the Service Configuration step, you can choose to run MongoDB as a service:

Select “Install MongoD as a Service”.
Choose either “Run service as Network Service user” or “Run service as a local or domain user”.
Set the “Data Directory” to C:Program FilesMongoDBServer{Version}data.
Set the “Log Directory” to C:Program FilesMongoDBServer{Version}log.

Note: Make sure you have created the above-mentioned directories or choose an existing one.

(Optional) Install MongoDB Compass:

You can choose to install MongoDB Compass, which is a graphical interface for MongoDB.
Click on the checkbox to opt-in or opt-out.

Complete the installation by clicking the “Install” button.

4. Add MongoDB to the System Path

Open the Control Panel and go to System and Security -> System -> Advanced System Settings -> Environment Variables.
In the System variables section, find the Path variable and select it, then click “Edit”.
Click “New” and add the path to the MongoDB bin directory. By default, it is:
C:Program FilesMongoDBServer{Version}bin
Click “OK”, then “Apply”, and “OK” again to close all dialogs.

5. Verify the Installation

Open Command Prompt (cmd).
Type mongo --version and press Enter.

This should display the version of MongoDB installed, verifying a successful installation.

Configuration

1. Create Configuration File

Open a text editor and create a configuration file named mongo.cfg.

Add the following basic configuration, modifying paths as necessary:

systemLog:
    destination: file
    path: C:Program FilesMongoDBServer{Version}logmongod.log
    logAppend: true
storage:
    dbPath: C:Program FilesMongoDBServer{Version}data
net:
    bindIp: 127.0.0.1
    port: 27017

Save this file in your MongoDB directory, e.g., C:Program FilesMongoDBServer{Version}mongo.cfg.

2. Run MongoDB with Configuration File

Open Command Prompt (cmd).
Run the following command to start MongoDB with the configuration file:
mongod --config "C:Program FilesMongoDBServer{Version}mongo.cfg"

This will start the MongoDB server based on the configurations provided in the mongo.cfg file.

Conclusion

You have successfully installed and configured MongoDB on your Windows machine. You can now start building and managing your MongoDB databases.

Installing MongoDB on macOS

Here is a practical step-by-step guide to installing MongoDB on a macOS system.

Prerequisites

Ensure you have Homebrew installed on your macOS. If not, you can install it by running the following command in the Terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Steps for Installation


  1. Update Homebrew
    Make sure your Homebrew is up to date by running:


    brew update


  2. Install MongoDB
    To install the latest version of MongoDB, execute the following command:


    brew tap mongodb/brew
    brew install mongodb-community@5.0

    This will install MongoDB 5.0, which is the latest stable version at the time of writing.



  3. Verify the Installation
    Confirm that MongoDB has been installed correctly by checking the version:


    mongod --version


  4. Run MongoDB as a Service
    To start MongoDB automatically as a service, use the following commands:


    brew services start mongodb/brew/mongodb-community

    You can stop the service using:


    brew services stop mongodb/brew/mongodb-community

    To check the status of the MongoDB service:


    brew services list


  5. Running MongoDB Manually
    If you prefer to run MongoDB manually, you can start the MongoDB server by running:


    mongod --config /usr/local/etc/mongod.conf

    To stop the MongoDB server, you can terminate the mongod process.



  6. Connect to MongoDB
    Open a new Terminal window/tab and launch the MongoDB shell to connect to the MongoDB instance:


    mongo

    This connects to the running instance of MongoDB and allows you to execute database operations.


Configuration


  1. Default Configuration File


    The default configuration file for MongoDB is usually located at /usr/local/etc/mongod.conf. You can edit this file to change configurations such as the data directory, log path, and bind IP address. Here is a quick way to open it via a text editor:


    nano /usr/local/etc/mongod.conf

    Example configuration snippet:


    storage:
    dbPath: /usr/local/var/mongodb
    systemLog:
    destination: file
    path: /usr/local/var/log/mongodb/mongo.log
    logAppend: true
    net:
    bindIp: 127.0.0.1


  2. Creating Data and Log Directories


    Ensure the directories specified in your configuration file exist:


    mkdir -p /usr/local/var/mongodb
    mkdir -p /usr/local/var/log/mongodb

    Adjust the permissions if needed:


    sudo chown -R `id -un` /usr/local/var/mongodb
    sudo chown -R `id -un` /usr/local/var/log/mongodb

Final Verification

Check the MongoDB server status by accessing the MongoDB shell and running sample queries or commands to verify full functionality:

mongo

You should see a prompt similar to:

MongoDB shell version v5.0.x
connecting to: mongodb://127.0.0.1:27017/
...
> show dbs

And that’s it! You’ve successfully installed and configured MongoDB on macOS.

Part 5: Installing MongoDB on Linux

Step-by-Step Installation

Here’s how you can install MongoDB on a Linux system:


  1. Import the MongoDB public GPG Key


    wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -


  2. Create a list file for MongoDB


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


  3. Reload local package database


    sudo apt-get update


  4. Install MongoDB packages


    sudo apt-get install -y mongodb-org


  5. Start MongoDB


    sudo systemctl start mongod


  6. Enable MongoDB to start on system reboot


    sudo systemctl enable mongod


  7. Verify that MongoDB has started


    You can check the status of the MongoDB service with the following command:


    sudo systemctl status mongod

If everything is set up correctly, you should see a status that indicates MongoDB is active and running.

Configuration

After installation, you might want to configure MongoDB to suit your needs. Configuration files are generally found at /etc/mongod.conf.

Example Configuration (Optional Changes):


  1. Open Configuration File


    sudo nano /etc/mongod.conf


  2. Modify BindIp to Allow Remote Connections (Optional)


    net:
    bindIp: 0.0.0.0


  3. Set Up Authentication (Optional)


    Edit the Security section to enable authentication.


    security:
    authorization: "enabled"


  4. Restart MongoDB to Apply Changes


    sudo systemctl restart mongod

Security Considerations


  1. Create an Admin User:


    After enabling authentication, create an admin user:


    use admin
    db.createUser({
    user: "myAdmin",
    pwd: "securePassword",
    roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
    })


  2. Connecting with Authentication:


    When authentication is enabled, use the -u (username) and -p (password) options:


    mongo -u "myAdmin" -p "securePassword" --authenticationDatabase "admin"

Conclusion

Following these steps will install MongoDB on your Linux system, start the service, and optionally configure it for remote connections and authentication. Ensure to restart the MongoDB service after any configuration changes for them to take effect.

Post-Installation Configuration and Management of MongoDB

Configuration


  1. Modify mongod.conf Configuration File


    The mongod.conf file is where you set most of MongoDB’s operational parameters. Typical locations:



    • Linux: /etc/mongod.conf

    • Windows: C:Program FilesMongoDBServer<version>binmongod.cfg

    • macOS: /usr/local/etc/mongod.conf


    Example of a mongod.conf:


    storage:
    dbPath: /var/lib/mongo
    journal:
    enabled: true
    systemLog:
    destination: file
    logAppend: true
    path: /var/log/mongodb/mongod.log
    net:
    port: 27017
    bindIp: 127.0.0.1 # Change to 0.0.0.0 to allow external connections
    security:
    authorization: enabled


  2. Enabling Authentication


    Verify that the authorization field is set to enabled under the security section:


    security:
    authorization: enabled

    Restart the MongoDB service to apply the changes.


User Management


  1. Create Admin User


    Open the MongoDB shell and connect to the admin database:


    mongo
    use admin

    Create an admin user:


    db.createUser({
    user: "admin",
    pwd: "securepassword",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
    });


  2. Create Application-Specific User


    Switch to the target database:


    use myAppDB

    Create the user:


    db.createUser({
    user: "appUser",
    pwd: "appUserPwd",
    roles: [ { role: "readWrite", db: "myAppDB" } ]
    });

Service Management

  1. Start and Stop MongoDB Service

    • Linux:
      sudo systemctl start mongod
      sudo systemctl stop mongod

    • Windows:
      net start MongoDB
      net stop MongoDB

    • macOS:
      brew services start mongodb/brew/mongodb-community
      brew services stop mongodb/brew/mongodb-community

  2. Enable MongoDB to Start on Boot

    • Linux:
      sudo systemctl enable mongod

    • Windows:
      sc config MongoDB start= auto

    • macOS:
      brew services start mongodb/brew/mongodb-community

Backup and Restore


  1. Backup MongoDB Database


    Use mongodump utility:


    mongodump --uri="mongodb://admin:securepassword@localhost:27017" --out=/path/to/backup/


  2. Restore MongoDB Database


    Use mongorestore utility:


    mongorestore --uri="mongodb://admin:securepassword@localhost:27017" /path/to/backup/

Monitoring and Maintenance

  1. Monitor the MongoDB Logs

    • Linux and macOS:
      tail -f /var/log/mongodb/mongod.log

    • Windows:
      Open the log file at the specified path in a text editor, typically:
      C:Program FilesMongoDBServer<version>logmongod.log

  2. Check Database Health


    Connect to MongoDB shell and run the following:


    use admin
    db.serverStatus()
    db.runCommand({ dbStats: 1 })


  3. Rotate Logs


    Issue a log rotation command as MongoDB does not rotate logs by default:


    db.adminCommand({ logRotate: 1 })

By following the steps outlined above, you can ensure that MongoDB is not only configured properly but also secured through user management and maintainable through proper service management and backup practices.

Related Posts