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
System Requirements đĨī¸
Before installing MongoDB, make sure your system meets the minimum requirements for the version you intend to use.
| Component | Minimum Requirement |
|---|---|
| Operating System | Windows 10+, macOS 12+, or a modern Linux distribution |
| RAM | At least 2 GB (4 GB+ recommended) |
| Disk Space | At least 1 GB free for the database and logs |
| CPU | 64-bit processor |
Note
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.0On 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-orgOn Windows, download the .msi installer from the official MongoDB download page and follow the setup wizard.
- Download the MSI installer for MongoDB Community Server.
- Run the installer and choose the Complete setup type.
- 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.
- Create a free account at MongoDB Atlas.
- Create a new Project and then a new Cluster, selecting the free M0 tier for development.
- Add a Database User with a username and password.
- Add your current IP address (or 0.0.0.0/0 for open access during development) under Network Access.
- Copy the provided connection string to use in your application.
Warning
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 mongoshVerifying Installation â
Once installed, confirm that MongoDB and its tools are correctly available on your PATH.
Verify installed versions
mongod --version
mongosh --versionTip
Starting the MongoDB Server đ
Start MongoDB via Homebrew services
brew services start mongodb-community@7.0Start MongoDB via systemd
sudo systemctl start mongodOn 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.0Stop MongoDB via systemd
sudo systemctl stop mongodMongoDB 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.1Data 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
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.logConnection 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=majorityCaution
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 myFirstDatabaseCreating Your First Collection đ
Creating a collection
db.createCollection("users");
db.users.insertOne({
name: "Alice",
email: "alice@example.com"
});Connecting with Compass đ§
- Open MongoDB Compass.
- Paste your connection string into the connection field.
- 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 myUserConnecting 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 mongodbBasic 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.
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/myFirstDatabaseLoading environment variables
require("dotenv").config();
const uri = process.env.MONGODB_URI;Danger
Development Workflow đ
- Start your local mongod instance or ensure your Atlas cluster is running.
- Use mongosh or Compass to inspect data during development.
- Write and test queries in isolation before integrating them into application code.
- 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=./backupRestore a database with mongorestore
mongorestore --uri="mongodb://localhost:27017" --db=myFirstDatabase ./backup/myFirstDatabaseImport & Export Tools đ¤
Export a collection to JSON
mongoexport --uri="mongodb://localhost:27017" --db=myFirstDatabase --collection=users --out=users.jsonImport a JSON file into a collection
mongoimport --uri="mongodb://localhost:27017" --db=myFirstDatabase --collection=users --file=users.jsonUpdating MongoDB âŦī¸
Update via Homebrew
brew update
brew upgrade mongodb-communityUpdate via apt
sudo apt update
sudo apt install --only-upgrade mongodb-orgWarning
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
Check if MongoDB is running
ps aux | grep mongodHint
Best Practices â
- Keep credentials out of source code using environment variables.
- Restrict bindIp and network access to trusted addresses only.
- Regularly back up data using mongodump or Atlas's automated backups.
- Pin a specific MongoDB major version in production to avoid unexpected breaking changes.
- Use Compass or mongosh to validate connectivity before writing application code.
Frequently Asked Questions â
Question
Answer
Question
Answer
Question
Answer
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.