Installation & Project Setup

Introduction 🌱

This tutorial walks you through everything needed to get MongoDB up and running, from installing the database itself to connecting it with a real application. Whether you plan to run MongoDB locally on your machine or use a cloud-hosted cluster via Atlas, this guide covers both paths in detail. By the end, you will have a fully working MongoDB environment and a basic project structure ready for development.

Information

Commands in this tutorial are shown for macOS, Linux, and Windows where they differ.

System Requirements đŸ–Ĩī¸

Before installing MongoDB, make sure your system meets the minimum requirements for the version you intend to use.

ComponentMinimum Requirement
Operating SystemWindows 10+, macOS 12+, or a modern Linux distribution
RAMAt least 2 GB (4 GB+ recommended)
Disk SpaceAt least 1 GB free for the database and logs
CPU64-bit processor

Note

Production deployments typically require significantly more RAM and disk space depending on working set size.

Installing MongoDB Community Edition đŸ“Ļ

The Community Edition is the free, open-source version of MongoDB, suitable for local development and self-managed deployments.

On macOS, the easiest method is using Homebrew.

Install MongoDB on macOS

brew tap mongodb/brew
brew update
brew install mongodb-community@7.0

On Ubuntu or Debian, MongoDB is installed via apt after adding the official repository.

Install MongoDB on Ubuntu

curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
  sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor

echo "deb [signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg] \
  https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | \
  sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

sudo apt update
sudo apt install -y mongodb-org

On Windows, download the .msi installer from the official MongoDB download page and follow the setup wizard.

  1. Download the MSI installer for MongoDB Community Server.
  2. Run the installer and choose the Complete setup type.
  3. Optionally install MongoDB Compass when prompted.

MongoDB Atlas Setup â˜ī¸

If you prefer not to manage a local server, MongoDB Atlas lets you spin up a fully managed cluster in the cloud within minutes.

  1. Create a free account at MongoDB Atlas.
  2. Create a new Project and then a new Cluster, selecting the free M0 tier for development.
  3. Add a Database User with a username and password.
  4. Add your current IP address (or 0.0.0.0/0 for open access during development) under Network Access.
  5. Copy the provided connection string to use in your application.

Warning

Never leave 0.0.0.0/0 network access enabled in a production environment; always restrict access to known IP ranges.

MongoDB Compass 🧭

Compass is the official graphical client for MongoDB, useful for browsing databases, running queries, and visualizing schema without writing raw commands. It can be downloaded separately from the MongoDB Compass page or installed alongside the Community Edition installer on Windows.

MongoDB Shell (mongosh) đŸ’ģ

mongosh is the modern command-line shell for interacting with MongoDB using full JavaScript syntax.

Install mongosh (if not bundled)

brew install mongosh

Verifying Installation ✅

Once installed, confirm that MongoDB and its tools are correctly available on your PATH.

Verify installed versions

mongod --version
mongosh --version

Tip

If these commands are not recognized, you may need to add MongoDB's bin directory to your system's PATH environment variable.

Starting the MongoDB Server 🚀

Start MongoDB via Homebrew services

brew services start mongodb-community@7.0

Start MongoDB via systemd

sudo systemctl start mongod

On Windows, MongoDB typically runs as a Windows Service named MongoDB, which starts automatically after installation.

Stopping the MongoDB Server 🛑

Stop MongoDB via Homebrew services

brew services stop mongodb-community@7.0

Stop MongoDB via systemd

sudo systemctl stop mongod

MongoDB Configuration âš™ī¸

MongoDB's behavior is controlled by a configuration file, usually named mongod.conf, written in YAML format.

Example mongod.conf

storage:
  dbPath: /var/lib/mongodb

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

net:
  port: 27017
  bindIp: 127.0.0.1

Data Directory đŸ—„ī¸

MongoDB stores all its data files under a data directory, controlled by the storage.dbPath configuration option. On most systems, the default path is /data/db or /var/lib/mongodb.

Important

Make sure the data directory exists and is writable before starting mongod for the first time.

Log Files 📋

MongoDB writes operational logs to the path defined in systemLog.path. These logs are essential for diagnosing startup failures and monitoring server activity.

Tail the MongoDB log

tail -f /var/log/mongodb/mongod.log

Connection Strings 🔗

A connection string (or URI) tells a client or driver how to reach a MongoDB server, including host, port, authentication, and options.

Connection string formats

mongodb://localhost:27017

mongodb+srv://username:password@cluster0.mongodb.net/myDatabase?retryWrites=true&w=majority

Caution

Never commit connection strings containing real credentials to a public repository.

Creating Your First Database 🆕

In MongoDB, databases are created implicitly — simply switching to a database name and inserting data will create it.

Creating a database with mongosh

use myFirstDatabase

Creating Your First Collection 📂

Creating a collection

db.createCollection("users");

db.users.insertOne({
  name: "Alice",
  email: "alice@example.com"
});

Connecting with Compass 🧭

  1. Open MongoDB Compass.
  2. Paste your connection string into the connection field.
  3. Click Connect to browse databases, collections, and documents visually.

Connecting with mongosh đŸ’ģ

Connect to a local server

mongosh "mongodb://localhost:27017"

Connect to an Atlas cluster

mongosh "mongodb+srv://cluster0.mongodb.net/myDatabase" --username myUser

Connecting from Node.js đŸŸĸ

The official mongodb driver allows Node.js applications to connect to and query a MongoDB server directly.

Install the driver

npm install mongodb

Basic connection example

const { MongoClient } = require("mongodb");

const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function main() {
  await client.connect();
  const db = client.db("myFirstDatabase");
  const users = db.collection("users");

  const result = await users.find({}).toArray();
  console.log(result);

  await client.close();
}

main();

Project Structure đŸ—ī¸

A clean project structure helps keep database logic organized and maintainable as an application grows.

my-mongo-app
package.json
.env
src
index.js

Environment Variables 🔐

Sensitive values such as connection strings and credentials should be stored in environment variables rather than hard-coded in source files.

.env

MONGODB_URI=mongodb+srv://myUser:myPassword@cluster0.mongodb.net/myFirstDatabase

Loading environment variables

require("dotenv").config();

const uri = process.env.MONGODB_URI;

Danger

Add .env to your .gitignore file to avoid leaking secrets into version control.

Development Workflow 🔄

  1. Start your local mongod instance or ensure your Atlas cluster is running.
  2. Use mongosh or Compass to inspect data during development.
  3. Write and test queries in isolation before integrating them into application code.
  4. Use seed scripts to populate consistent test data across environments.

MongoDB Tools 🧰

MongoDB ships with several command-line utilities beyond mongod and mongosh for administration and data management.

  • mongodump and mongorestore — for backup and restore.
  • mongoimport and mongoexport — for importing and exporting data.
  • mongostat and mongotop — for real-time performance monitoring.

Backup Tools 💾

Backup a database with mongodump

mongodump --uri="mongodb://localhost:27017" --db=myFirstDatabase --out=./backup

Restore a database with mongorestore

mongorestore --uri="mongodb://localhost:27017" --db=myFirstDatabase ./backup/myFirstDatabase

Import & Export Tools 📤

Export a collection to JSON

mongoexport --uri="mongodb://localhost:27017" --db=myFirstDatabase --collection=users --out=users.json

Import a JSON file into a collection

mongoimport --uri="mongodb://localhost:27017" --db=myFirstDatabase --collection=users --file=users.json

Updating MongoDB âŦ†ī¸

Update via Homebrew

brew update
brew upgrade mongodb-community

Update via apt

sudo apt update
sudo apt install --only-upgrade mongodb-org

Warning

Always review the official release notes before upgrading a production deployment across major versions.

Common Installation Issues 🐛

  • Port already in use: another process may already be bound to port 27017.
  • Permission denied on the data directory due to incorrect file ownership.
  • mongod or mongosh not recognized because the installation directory is missing from PATH.
  • Firewall rules blocking connections to a remote Atlas cluster.

Troubleshooting 🔧

Example

If mongod fails to start, check the log file first — most startup errors, such as a locked data directory or invalid config syntax, are clearly reported there.

Check if MongoDB is running

ps aux | grep mongod

Hint

On Atlas, connection issues are most often caused by an IP address not being whitelisted under Network Access.

Best Practices ✅

  1. Keep credentials out of source code using environment variables.
  2. Restrict bindIp and network access to trusted addresses only.
  3. Regularly back up data using mongodump or Atlas's automated backups.
  4. Pin a specific MongoDB major version in production to avoid unexpected breaking changes.
  5. Use Compass or mongosh to validate connectivity before writing application code.

Frequently Asked Questions ❓

Question

Do I need to install MongoDB locally if I use Atlas?

Answer

No, but installing mongosh locally is still recommended for connecting to and managing your Atlas cluster from the command line.

Question

What port does MongoDB use by default?

Answer

MongoDB listens on port 27017 by default.

Question

Can I run multiple MongoDB versions on the same machine?

Answer

Yes, though it requires careful management of binaries, dbPath locations, and configuration files to avoid conflicts.

Summary 📝

You have now learned how to install MongoDB locally or configure it via Atlas, verify the installation, start and stop the server, and connect using Compass, mongosh, and Node.js. You also explored project structure, environment variables, and essential tooling for backups and data import/export.

What's Next? 🚀

  • Learn CRUD operations in depth using mongosh and the Node.js driver.
  • Explore schema validation to enforce structure on your collections.
  • Set up indexes to optimize query performance.
  • Deploy your application against a production-ready MongoDB Atlas cluster.