Showing posts with label NoSQL Database. Show all posts
Showing posts with label NoSQL Database. Show all posts

How to Install MongoDB on Windows, Linux & macOS (Step-by-Step)

๐Ÿงฐ Installing MongoDB: A Simple Guide for Everyone

Welcome to this tutorial on installing MongoDB.

MongoDB is like a super smart digital filing cabinet that helps you store and organize large amounts of information quickly and easily. It is widely used by websites, apps, and games to manage data.

Whether you're a beginner just starting out or an expert needing a quick refresher, this guide will help you install MongoDB on Windows, Linux, or macOS.

Think of MongoDB as a box of LEGO bricks: each “brick” holds information, and you can stack them however you want. There are no strict table rules like traditional databases.


๐Ÿ“‘ Table of Contents


๐Ÿ“– What is MongoDB and Why Use It?

MongoDB is a NoSQL database, meaning it doesn’t use tables like old-school relational databases. Instead, it stores data in flexible “documents” similar to JSON files.

Benefits:

  • For beginners: Easy to learn, no complex SQL needed.
  • For experts: Scalable, supports sharding, and offers powerful querying.

๐Ÿงช System Requirements

OS Minimum Version Notes
Windows 64-bit, Windows 10+ Chocolatey or manual install
Linux Ubuntu 20.04+, CentOS 8+ APT or manual install supported
macOS 11 (Big Sur)+ Intel & Apple Silicon supported

๐Ÿ‘‰ Download MongoDB from the official website: https://www.mongodb.com


⚡ Method 1: Install Using Package Managers (Recommended)

Package managers are like app stores for your computer, handling downloads, installations, and updates automatically.

๐Ÿง Linux (Ubuntu/Debian)

  1. Update your system:
    sudo apt update
    sudo apt upgrade -y
  2. Add MongoDB GPG key & repository:
    wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
    echo "deb [ arch=amd64,arm64 ] 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
  3. Install MongoDB:
    sudo apt install -y mongodb-org
  4. Start and enable MongoDB:
    sudo systemctl start mongod
    sudo systemctl enable mongod
  5. Test the installation:
    mongosh
    > db.version()

๐Ÿ’ก Pro Tip: Use mongod --config /etc/mongod.conf for custom configs (e.g., bind IP or authentication).

๐ŸŽ macOS (Homebrew)

  1. Install Homebrew:
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
  2. Tap and install MongoDB:
    brew tap mongodb/brew
    brew install mongodb-community@7.0
  3. Start MongoDB as a service:
    brew services start mongodb/brew/mongodb-community
  4. Or run manually:
    mongod --config /opt/homebrew/etc/mongod.conf
  5. Test:
    mongosh

๐ŸชŸ Windows (Chocolatey)

  1. Install Chocolatey from https://chocolatey.org.
  2. Open PowerShell as Administrator and run:
    choco install mongodb
  3. MongoDB installs as a Windows service and starts automatically.
  4. Test:
    mongosh

⚠️ If Chocolatey isn’t available, use the manual installation method below.


๐Ÿงฐ Method 2: Manual Installation (For More Control)

This method is great for learning how MongoDB works under the hood or troubleshooting advanced setups.

๐ŸชŸ Windows Manual Installation

  1. Download the MSI installer from MongoDB download page.
  2. Run the installer, choose “Complete” setup, and check “Install MongoDB as a Service”.
  3. Create the data directory:
    mkdir C:\data\db
  4. Start MongoDB manually (if not installed as a service):
    "C:\Program Files\MongoDB\Server\7.0\bin\mongod.exe"
  5. (Optional) Add MongoDB to PATH:
    C:\Program Files\MongoDB\Server\7.0\bin
  6. Troubleshooting:
    • If port 27017 is busy, change port with --port 27018.
    • Advanced config: edit mongod.cfg in the install directory.

๐Ÿง Linux Manual Installation (e.g., CentOS/RHEL)

  1. Download the TGZ package for your distro.
  2. Extract and move:
    tar -xzf mongodb-linux-x86_64-7.0.tgz
    sudo mkdir -p /opt/mongodb
    sudo mv mongodb-linux-x86_64-7.0 /opt/mongodb
  3. Add to PATH:
    export PATH=$PATH:/opt/mongodb/bin
    source ~/.bashrc
  4. Create the data directory:
    sudo mkdir -p /data/db
    sudo chown $(whoami) /data/db
  5. Run MongoDB:
    mongod

๐ŸŽ macOS Manual Installation (Without Homebrew)

  1. Download TGZ for macOS (Intel or ARM).
  2. Extract and move:
    sudo mkdir -p /opt/mongodb
    sudo tar -xzf mongodb-macos-x86_64-7.0.tgz -C /opt/mongodb
  3. Symlink binaries:
    sudo ln -s /opt/mongodb/bin/* /usr/local/bin/
  4. Create data dir and run (same as Linux).
  5. For Apple Silicon: use the ARM64 build and verify with:
    file mongod

✅ Verifying Installation (All OS)

  1. Open MongoDB Shell:
    mongosh
  2. Check connection:
    db.runCommand({ connectionStatus: 1 })
  3. Check version:
    mongod --version

⚠️ If mongosh isn’t found, make sure your PATH includes the bin directory.


๐Ÿ” Post-Installation Best Practices

Enable Authentication

use admin
db.createUser({
  user: "admin",
  pwd: "strongpassword",
  roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
})

Edit mongod.conf:

security:
  authorization: enabled

Restart MongoDB service after making changes.

Bind IP & Firewall

  • Bind IP: For remote access, set net.bindIp: 0.0.0.0 (secure with firewall).
  • Firewall:
    • Windows: Allow port 27017
    • Linux: sudo ufw allow 27017
    • macOS: System Preferences → Security → Firewall

Updates

  • Package Manager: sudo apt upgrade mongodb-org or brew upgrade
  • Manual: Download new version and backup /data/db

๐Ÿงน Uninstall or Upgrade MongoDB

If you ever need to remove or upgrade MongoDB, here are quick steps by OS:

๐Ÿง Linux (Ubuntu/Debian)

sudo systemctl stop mongod
sudo apt purge mongodb-org*
sudo rm -r /var/log/mongodb
sudo rm -r /var/lib/mongodb

๐ŸŽ macOS (Homebrew)

brew services stop mongodb/brew/mongodb-community
brew uninstall mongodb/brew/mongodb-community
rm -rf /usr/local/var/mongodb

๐ŸชŸ Windows

  1. Stop the MongoDB service from Services.msc or with:
    net stop MongoDB
  2. Uninstall from Control Panel or:
    choco uninstall mongodb
  3. Delete C:\data\db if you want to remove stored databases.

To upgrade, simply download the new version and follow the same installation method. Always backup your data directory before upgrading.


๐Ÿš€ Performance Tips for Experts

  • Use WiredTiger storage engine (default).
  • Store storage.dbPath on SSD.
  • Monitor performance with:
    mongostat
    or use MongoDB Compass GUI.

๐Ÿง  Tools and Next Steps

  • MongoDB Compass: GUI tool to visualize databases.
  • Drivers: Install via pip (Python), npm (Node.js), etc.
  • Backup: Use mongodump for safe exports.


๐Ÿ”— Official Documentation & References


๐Ÿ‘‰ Beginner project:

use mydb
db.users.insertOne({ name: "Alice", age: 10 })

๐Ÿงญ Practice on a virtual machine first.
For issues, check logs in:

  • /var/log/mongodb (Linux)
  • Install dir (Windows/macOS)

❓ Frequently Asked Questions (FAQ)

1. How do I check if MongoDB is installed correctly?

Open your terminal or command prompt and run:

mongosh

If the shell opens, run:

db.runCommand({ connectionStatus: 1 })

You should see "ok" : 1 in the output.

2. Where is MongoDB installed on my system?

  • Windows: C:\Program Files\MongoDB\Server\7.0\bin
  • Linux: /usr/bin or /opt/mongodb/bin
  • macOS: /usr/local/bin or Homebrew directory

3. What port does MongoDB use?

MongoDB uses port 27017 by default. You can change it in mongod.conf using:

net:
  port: 27018

4. How do I uninstall MongoDB?

Follow the uninstall steps in the Uninstall / Upgrade section of this article for your OS.

5. How do I secure my MongoDB installation?

  • Enable authentication and create an admin user.
  • Use net.bindIp: 127.0.0.1 or firewall rules to limit access.
  • Keep your MongoDB version up to date.

6. Can I run MongoDB on a virtual machine?

Yes. MongoDB runs well on virtual machines or containers like Docker. This is a great way to practice without affecting your main system.

Feel free to ask in comment if you have any question or suggestions.๐ŸŽ‰ Happy coding!

Normalization vs Denormalization: SQL vs MongoDB Practice task Solution

Solution: Normalization vs Denormalization Practice


This tutorial provides the complete solution to the earlier practice task comparing normalization in SQL and denormalization in MongoDB. If you haven't attempted the exercise, click here to try it first.

Here's the full solution to the Normalization vs Denormalization practice exercise using both SQL (normalized) and MongoDB (denormalized) approaches.


๐Ÿ”น Task A: Normalized Design (SQL Style)


1. Table Structure

Authors Table

CREATE TABLE Authors (
  AuthorID INT PRIMARY KEY,
  AuthorName VARCHAR(100),
  Email VARCHAR(100)
);

Books Table

CREATE TABLE Books (
  BookID INT PRIMARY KEY,
  Title VARCHAR(150),
  AuthorID INT,
  FOREIGN KEY (AuthorID) REFERENCES Authors(AuthorID)
);


2. Sample Data Insertion

INSERT INTO Authors (AuthorID, AuthorName, Email) VALUES
(1, 'Jane Austen', 'jane.austen@example.com'),
(2, 'Mark Twain', 'mark.twain@example.com');

INSERT INTO Books (BookID, Title, AuthorID) VALUES
(101, 'Pride and Prejudice', 1),
(102, 'Emma', 1),
(103, 'Adventures of Tom Sawyer', 2);


3. SQL Query to Join Data

SELECT Books.Title, Authors.AuthorName
FROM Books
JOIN Authors ON Books.AuthorID = Authors.AuthorID;

๐Ÿ” Expected Output:


+----------------------------+-------------+
| Title                      | AuthorName  |
+----------------------------+-------------+
| Pride and Prejudice        | Jane Austen |
| Emma                       | Jane Austen |
| Adventures of Tom Sawyer   | Mark Twain  |
+----------------------------+-------------+


๐Ÿ”น Task B: Denormalized Design (MongoDB Style)


1. Book Documents with Embedded Author Info

db.books.insertMany([
  {
    book_id: 101,
    title: "Pride and Prejudice",
    author: {
      author_id: 1,
      name: "Jane Austen",
      email: "jane.austen@example.com"
    }
  },
  {
    book_id: 102,
    title: "Emma",
    author: {
      author_id: 1,
      name: "Jane Austen",
      email: "jane.austen@example.com"
    }
  },
  {
    book_id: 103,
    title: "Adventures of Tom Sawyer",
    author: {
      author_id: 2,
      name: "Mark Twain",
      email: "mark.twain@example.com"
    }
  }
]);


2. MongoDB Query to Find Books by Author Name

db.books.find({ "author.name": "Jane Austen" }, { title: 1, _id: 0 });

๐Ÿ” Expected Output:


[
  { title: "Pride and Prejudice" },
  { title: "Emma" }
]

๐Ÿ”ธ Bonus Challenge: Updating Author Email


๐Ÿง  In Normalized (SQL):

  • You update once in the Authors table:

UPDATE Authors
SET Email = 'new.jane.austen@example.com'
WHERE AuthorID = 1;

Change is reflected across all books automatically (since books reference the author ID).


๐Ÿง  In Denormalized (MongoDB):

  • You must update all documents containing the embedded author data:

db.books.updateMany(
  { "author.author_id": 1 },
  { $set: { "author.email": "new.jane.austen@example.com" } }
);

❗ Requires multiple updates — more effort, but often better read performance.

๐Ÿ”— Want a deeper look at MongoDB's schema design strategies? Check out our MongoDB Schema Design Guide.


✅ Summary: What You’ve Learned


Concept SQL MongoDB (NoSQL)
Data Structure Normalized into separate tables Denormalized with embedded docs
Redundancy Low High
Update Effort One update in Authors table Multiple document updates
Read Simplicity Needs JOIN Direct query, no joins needed

๐Ÿ That’s it! You now understand the core differences between normalized and denormalized database design using SQL and MongoDB. Got questions or want more practice? Let us know in the comments or check out more tutorials in our Learning Series.


Featured Post

How to Install MongoDB on Windows, Linux & macOS (Step-by-Step)

๐Ÿงฐ Installing MongoDB: A Simple Guide for Everyone Welcome to this tutorial on installing MongoDB . MongoDB is like a super smart digita...

Popular Posts