Installation and Setup

In this chapter, we will cover everything you need to know about installing and setting up MongoDB on various platforms. Whether you are using Windows, macOS, or Linux, this guide will take you from basic installation to advanced configuration, ensuring you have a comprehensive understanding of the process.

System Requirements

Before installing MongoDB, ensure that your system meets the minimum requirements:

  • Operating System: Windows, macOS, or Linux
  • RAM: At least 2GB (4GB or more recommended)
  • Disk Space: Minimum 200MB of free space for installation, additional space required for data storage

Installing MongoDB on Various Platforms

Installing MongoDB on Windows

Download MongoDB:

Run the Installer:

  • Follow the prompts in the MongoDB installer.
  • Select “Complete” setup type.
  • Make sure “Install MongoDB Compass” is selected if you want to install the graphical interface.

Add MongoDB to the System Path:

  • Open the Control Panel and navigate to System and Security > System > Advanced system settings.
  • Click on Environment Variables, find the Path variable, and add the path to the MongoDB binaries (e.g., C:\Program Files\MongoDB\Server\4.4\bin).

Start MongoDB:

  • Open a Command Prompt and run the following command to start the MongoDB server
				
					mongod

				
			

To run MongoDB as a service, use the following command:

				
					net start MongoDB

				
			

Installing MongoDB on macOS

Install Homebrew (if 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@4.4

				
			

Start MongoDB:

				
					brew services start mongodb/brew/mongodb-community

				
			

Installing MongoDB on Linux

Ubuntu

Import the MongoDB public key:

				
					wget -qO - https://www.mongodb.org/static/pgp/server-4.4.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/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list

				
			

Reload the 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

				
			

Configuring MongoDB

Configuration File

MongoDB’s configuration is managed through a file called mongod.conf. This file is typically located in the /etc directory on Linux, or in the MongoDB installation directory on Windows and macOS.

Key Configuration Options

Storage Configuration:

				
					storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

				
			

System Log Configuration:

				
					systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

				
			

Network Configuration:

				
					net:
  port: 27017
  bindIp: 127.0.0.1

				
			

Running MongoDB

Starting and Stopping MongoDB

On Windows

To start MongoDB:

				
					net start MongoDB

				
			

To stop MongoDB:

				
					net stop MongoDB

				
			

On macOS and Linux

To start MongoDB:

				
					sudo systemctl start mongod

				
			

To stop MongoDB:

				
					sudo systemctl stop mongod

				
			

Running MongoDB as a Service

On Linux, you can enable MongoDB to start automatically on boot:

				
					sudo systemctl enable mongod

				
			

On macOS, you can use Homebrew to start MongoDB as a service:

				
					brew services start mongodb/brew/mongodb-community

				
			

Connecting to MongoDB

MongoDB Shell

The MongoDB shell (mongo) is an interactive JavaScript interface to MongoDB. You can use it to query and update data, and perform administrative operations.

To connect to the MongoDB shell:

				
					mongo

				
			

MongoDB Compass

MongoDB Compass is a graphical user interface that allows you to visualize and interact with your data. You can download it from the MongoDB website.

Connecting with a Programming Language

You can connect to MongoDB using various programming languages. Here is an example using Node.js and the mongodb package:

Install the MongoDB package:

				
					npm install mongodb

				
			

Connect to MongoDB:

				
					const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function run() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");
  } finally {
    await client.close();
  }
}

run().catch(console.dir);

				
			
				
					// Output 
Connected to MongoDB

				
			

Basic Security Setup

Enabling Authentication

To enable authentication, edit the mongod.conf file:

				
					security:
  authorization: "enabled"

				
			

Creating Users

You can create users with specific roles and privileges. Here is an example using the MongoDB shell:

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

				
			
				
					{
  "ok": 1
}

				
			

Advanced Configuration

Enabling Replica Sets

Replica sets provide high availability and data redundancy. To configure a replica set, edit the mongod.conf file:

				
					replication:
  replSetName: "rs0"

				
			

Initialize the replica set using the MongoDB shell:

				
					rs.initiate()

				
			

Configuring Sharding

Sharding distributes data across multiple servers. To configure sharding, start a mongos instance and add shards:

Start a mongos instance:

				
					mongos --configdb configReplSet/host1:port1,host2:port2,host3:port3

				
			

Add shards using the MongoDB shell:

				
					sh.addShard("shardReplSet/host1:port1")
sh.addShard("shardReplSet/host2:port2")

				
			

In this chapter, we covered the installation and setup process of MongoDB, from system requirements to advanced configurations like replica sets and sharding. We discussed how to install MongoDB on Windows, macOS, and Linux, and how to configure it using the mongod.conf file. We also explored how to connect to MongoDB using the MongoDB shell, MongoDB Compass, and programming languages like Node.js. Finally, we touched on basic security setup and advanced configurations to ensure your MongoDB instance is secure and scalable.Happy coding !❤️

Table of Contents