0% found this document useful (0 votes)
8 views25 pages

NoSQL and MongoDB Overview Guide

This document provides an overview of NoSQL databases, particularly focusing on MongoDB, which is a popular document-based NoSQL database. It covers key concepts, commands, advantages, use cases, user account management, access control, and how to connect MongoDB with Node.js. Additionally, it includes practical steps for setting up MongoDB on a Windows environment and managing collections and databases.

Uploaded by

dineshgdx
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views25 pages

NoSQL and MongoDB Overview Guide

This document provides an overview of NoSQL databases, particularly focusing on MongoDB, which is a popular document-based NoSQL database. It covers key concepts, commands, advantages, use cases, user account management, access control, and how to connect MongoDB with Node.js. Additionally, it includes practical steps for setting up MongoDB on a Windows environment and managing collections and databases.

Uploaded by

dineshgdx
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 5

Understanding NoSQL and MongoDB

What is NoSQL?

NoSQL stands for “Not Only SQL.”


It refers to non-relational database systems that are different from traditional SQL databases
(like MySQL, Oracle, PostgreSQL).

Purpose:
Designed to handle large-scale data, unstructured or semi-structured data, and high-
performance applications (like real-time analytics, IoT, social media, etc.).

Difference Between SQL and NoSQL

Feature SQL Databases NoSQL Databases

Documents, Key-Value, Graphs, or Wide-Column


Data Model Tables (rows and columns)
stores

Schema Fixed schema Dynamic/flexible schema

Vertical (add more


Scalability Horizontal (add more servers/nodes)
CPU/RAM)

Examples MySQL, PostgreSQL, Oracle MongoDB, Cassandra, Redis, Neo4j

Query Structured Query Language Query syntax depends on type (e.g., JSON in
Language (SQL) MongoDB)

Complex queries,
Best For Big Data, fast-changing or unstructured data
transactions

Types of NoSQL Databases

Type Description Example

Document-based Stores data as JSON/BSON documents MongoDB, CouchDB

Key-Value Store Stores data as key–value pairs Redis, DynamoDB

Column-based Stores data in columns instead of rows Cassandra, HBase


Type Description Example

Graph-based Stores data as nodes and relationships Neo4j, OrientDB

MongoDB Overview

MongoDB is the most popular NoSQL document-based database.


It stores data in JSON-like documents called BSON (Binary JSON).

Key Concepts:

Term Description SQL Equivalent

Database Collection of collections Database

Collection Group of related documents Table

Document JSON-like record Row

Field Key-value pair in a document Column

Example: MongoDB Document

"_id": 1,

"name": "Alex",

"email": "alex@[Link]",

"skills": ["JavaScript", "[Link]", "MongoDB"],

"experience": {

"company": "TechCorp",

"years": 2

}
Basic MongoDB Commands

Command Description

show dbs List all databases

use mydb Switch or create a database

[Link]("students") Create a collection

[Link]({...}) Insert one document

[Link]() Retrieve documents

[Link]({...}) Update a document

[Link]({...}) Delete a document

Advantages of MongoDB

• Flexible and schema-less

• High performance and scalability

• Easy to use with modern web technologies ([Link], Express, etc.)

• Built-in replication and sharding for fault tolerance and load balancing

• Supports aggregation, indexing, and MapReduce operations

Use Cases

• Social networks (user profiles, posts)

• Real-time analytics dashboards

• Content management systems

• IoT and mobile app backends

• E-commerce product catalogs


MongoDB environment

(Windows-focused) you can use for development with mongod (server), mongosh (shell),
MongoDB Compass, and [Link] (to connect from apps).

1) Overview — what we’ll set up

• MongoDB Server (mongod) — Community Edition

• MongoDB Shell (mongosh)

• MongoDB Compass (GUI) — optional but handy

• [Link] + npm (for connecting with mongodb or mongoose)

• VS Code and MongoDB extension (optional)

• Configure PATH, create data folder, optionally run MongoDB as Windows Service

2) Download & install

1. MongoDB Community Server (MSI)

o Download from MongoDB site (Community Server). Run the MSI and choose
Complete.

o During install: you can check “Install MongoDB as a Service” (recommended for
dev). Note the installation path (usually C:\Program
Files\MongoDB\Server\<version>\).

2. MongoDB Shell (mongosh)

o If the server MSI didn’t include mongosh, install the MongoDB Shell MSI
separately. During install, check Add mongosh to PATH.

3. MongoDB Compass (optional)

o Download and install Compass to browse collections visually.

4. [Link] (LTS)

o Install [Link] (LTS). This provides node and npm.

5. VS Code (optional)

o Install Visual Studio Code for editing and debugging. Add the MongoDB for VS
Code extension if you want in-editor DB browsing.
3) Create data directory (if running mongod manually)

Open PowerShell as Administrator and run:

md C:\data\db

If you installed as a service this may not be necessary but it’s safe to have.

4) Set PATH (if installers didn’t)

Make sure the executables are reachable from any terminal.

Common paths to add to System PATH:

C:\Program Files\MongoDB\Server\<version>\bin

C:\Program Files\MongoDB\mongosh\bin # if mongosh installed separately

How: Windows → Run [Link] → Advanced → Environment Variables → Edit Path → New →
paste path → OK → reopen terminal.

Verify:

mongod --version

mongosh --version

5) Start MongoDB server

If installed as Windows Service (recommended)

Start service:

net start MongoDB

Stop service:

net stop MongoDB

6) Connect with mongosh (shell)

Simple local connect (default host/port):

mongosh

Or explicit:

mongosh "mongodb://[Link]:27017"
Basic commands inside mongosh:

show dbs

use mydb

[Link]("students")

[Link]({name:"Alex", age:21})

[Link]().pretty()

exit

7) Connect from [Link] (quick example)

Example in Code ([Link] + MongoDB)

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

const uri = "mongodb://localhost:27017";

const client = new MongoClient(uri);

async function run() {

try {

await [Link]();

const db = [Link]("school");

const students = [Link]("students");

await [Link]({ name: "John", grade: "A", age: 20 });

const data = await [Link]().toArray();


Run:
[Link](data);
In VS Code Terminal:
} finally {
cd C:\Users\Lenovo\MongoDB
await [Link]();
npm init -y
}
npm install mongodb
}
Then run your script:
run().catch([Link]);
node [Link]
User Accounts in MongoDB

MongoDB uses a Role-Based Access Control (RBAC) system — meaning every user has roles, and
those roles define what actions they can perform.

A. What is a MongoDB User?

A user account is a set of credentials (username + password) used to:

• Authenticate into MongoDB.

• Access only specific databases.

• Perform actions according to assigned roles.

B. Creating a User Account

Step 1: Start MongoDB normally (no authentication)

mongod --dbpath C:\data\db

Step 2: Open mongosh

mongosh

Step 3: Switch to the admin database

use admin

Step 4: Create the first admin user

[Link]({

user: "adminuser",

pwd: "admin123",

roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]

})

This user can create/manage other users across all databases.

C. Creating Regular Users

After enabling authentication (explained later), log in as the admin user and create application
users.

Example – Application User

use schoolDB
[Link]({

user: "alex",

pwd: "alex123",

roles: [ { role: "readWrite", db: "schoolDB" } ]

})

Now “alex” can read and write data in the schoolDB database only.

Access Control in MongoDB

Access control determines:

Who can connect (authentication) and what they can do (authorization).

A. Authentication

To secure your MongoDB, you must enable authentication.

Enable temporarily (manual start):

mongod --auth --dbpath C:\data\db

Enable permanently (config file):

Edit the MongoDB config file, typically found at:

C:\Program Files\MongoDB\Server\<version>\bin\[Link]

Add or edit:

security:

authorization: enabled

Restart the MongoDB service:

net stop MongoDB

net start MongoDB

Now authentication is always required.

B. Authorization (Roles and Privileges)

MongoDB users are assigned roles that define what actions they can perform.
Role Database Access Type Description

read specific DB Read-only Can only view data

readWrite specific DB Read + Write Can view and modify data

dbAdmin specific DB Administrative Can manage collections, indexes

userAdmin specific DB Manage users Can create/manage users on that DB

readWriteAnyDatabase all DBs Read + Write Access across all databases

userAdminAnyDatabase all DBs Manage users Create users in any DB

root all DBs Superuser Full access to everything

C. Managing Users and Roles

View all users in the current DB:

show users

View a specific user:

[Link]("alex")

Change a user’s password:

[Link]("alex", { pwd: "newPass123" })

Add or remove roles:

[Link]("alex", [{ role: "dbAdmin", db: "schoolDB" }])

[Link]("alex", [{ role: "dbAdmin", db: "schoolDB" }])

Delete a user:

[Link]("alex")
Administering Databases in MongoDB

The admin database is special — it stores user credentials and administrative information.

When you connect as an admin, you can:

• Create or drop databases

• Manage users

• Assign roles

• Perform backup and restore operations

A. Switching Databases

use salesDB

If the database doesn’t exist, it will be created automatically when you add data.

B. Creating Collections

[Link]("employees")

Insert data:

[Link]({ name: "John", role: "Manager" })

List all collections:

show collections

Drop a collection:

[Link]()

C. Viewing and Managing Databases

List all databases:

show dbs

Drop a database:

[Link]()

Rename or copy data — not directly supported by command, but you can export/import with
mongodump and mongorestore.
D. Database-Level Roles

Role Scope Description

read DB Read only

readWrite DB Read/write

dbAdmin DB Manage collections, indexes

userAdmin DB Manage users

dbOwner DB Combines readWrite, dbAdmin, userAdmin

E. Monitoring and Maintenance Commands

Command Description

[Link]() Shows database statistics

[Link]() Displays server performance info

[Link]() Lists running operations

[Link](opid) Stops a long-running operation

[Link]() Lists all collections

[Link]() Repairs and compacts the database

Example: Full Admin Flow

Let’s see a real setup example

# Start MongoDB

mongod --auth --dbpath C:\data\db

# Open mongosh

mongosh

use admin

# 1. Create admin user

[Link]({
user: "rootAdmin",

pwd: "root123",

roles: [ { role: "root", db: "admin" } ]

})

# 2. Exit, then reconnect as admin

exit

mongosh -u rootAdmin -p root123 --authenticationDatabase admin

# 3. Create application database and user

use companyDB

[Link]({

user: "employee",

pwd: "emp123",

roles: [ { role: "readWrite", db: "companyDB" } ]

})

# 4. Verify users

show users

# 5. Test access

exit

mongosh -u employee -p emp123 --authenticationDatabase companyDB

use companyDB

[Link]({ name: "Alice" })

show collections
Collection in MongoDB

What is a Collection in MongoDB?

A collection in MongoDB is equivalent to a table in relational databases like MySQL.

• It stores documents (records) in BSON (Binary JSON) format.

• Each document can have different fields — no fixed schema required.

• Collections exist inside a database.

Example Analogy:

SQL Concept MongoDB Equivalent

Database Database

Table Collection

Row Document

Column Field

Creating and Managing Collections in MongoDB

1. Create a Collection

MongoDB automatically creates a collection when you first insert data into it.

Example (using mongosh):

use myDatabase // switch or create database

[Link]("students")

Output:

{ "ok" : 1 }

2. Insert Documents into Collection

Once created, you can insert data into the collection.

[Link]({

name: "Alex",

age: 21,
course: "Soft Computing"

})

[Link]([

{ name: "John", age: 22, course: "AI" },

{ name: "Maya", age: 23, course: "ML" }

])

3. View Collections

To list all collections in the current database:

show collections

or:

[Link]()

4. Read Documents

Fetch all documents:

[Link]()

Find specific data:

[Link]({ name: "Alex" })

5. Update Documents

Update one document:

[Link](

{ name: "Alex" },

{ $set: { age: 22 } }

Update many:

[Link](

{ course: "AI" },

{ $set: { course: "Artificial Intelligence" } }


)

6. Delete Documents

Delete one:

[Link]({ name: "Maya" })

Delete all documents matching a filter:

[Link]({ course: "ML" })

7. Drop (Delete) a Collection

To remove the entire collection:

[Link]()

Output:

true

8. List All Databases

show dbs

Switch to a specific database:

use myDatabase

Example Workflow Summary

// 1. Create or switch database

use collegeDB

// 2. Create collection

[Link]("students")

// 3. Insert documents

[Link]([

{ name: "Alex", course: "Soft Computing", marks: 85 },

{ name: "John", course: "AI", marks: 90 },

{ name: "Maya", course: "ML", marks: 95 }

])
// 4. Find students with marks > 85

[Link]({ marks: { $gt: 85 } })

// 5. Update course name

[Link]({}, { $set: { semester: "7th" } })

// 6. Delete one student

[Link]({ name: "Maya" })

// 7. Drop the collection

[Link]()

Key Notes

• No schema needed — fields can differ between documents.

• Collections grow dynamically as documents are added.

• Indexes can be created on fields for faster querying.

Connect MongoDB with [Link]

how to connect MongoDB with [Link], using both local MongoDB and MongoDB Atlas
(cloud).

Step 1: Install [Link] and MongoDB driver

First, ensure [Link] is installed.


Then create a new folder for your project and run these commands in the terminal:

mkdir mongo-connection-demo

cd mongo-connection-demo

npm init -y

npm install mongodb

Step 2: Create a Connection File

Create a file named [Link] and add the following code.


Example 1: Connect to Local MongoDB

// [Link]
const { MongoClient } = require("mongodb");
// Replace with your local connection string
const uri = "mongodb://[Link]:27017";
// Create a new client instance
const client = new MongoClient(uri);
async function run() {
try {
// Connect to MongoDB
await [Link]();

[Link](" Connected to MongoDB (local)");


// Select database and collection
const db = [Link]("collegeDB");
const students = [Link]("students");
// Insert sample data
await [Link]({ name: "Alex", course: "Soft Computing", marks: 85 });
// Fetch data
const all = await [Link]().toArray();

[Link](" Students:", all);


} catch (err) {

[Link](" Connection error:", err);


} finally {
await [Link]();

[Link](" Connection closed");


}
}
run();
Output:

Connected to MongoDB (local)

Students: [ { _id: ..., name: 'Alex', course: 'Soft Computing', marks: 85 } ]

Connection closed

Step 3: Connect to MongoDB Atlas (Cloud)

MongoDB Atlas provides a free cloud-hosted database.

Steps:

1. Go to [Link]

2. Create a cluster → Get your Connection String

3. Replace <username>, <password>, and <dbname> in the URI:

4. mongodb+srv://<username>:<password>@[Link]/<dbname>?retryWrit
es=true&w=majority

Example 2: Connect to MongoDB Atlas

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

// Replace <username>, <password>, and <dbname> with your details

const uri =
"mongodb+srv://alex:<password>@[Link]/collegeDB?retryWrites=true&w=maj
ority";

const client = new MongoClient(uri);

async function run() {

try {

await [Link]();

[Link](" Connected to MongoDB Atlas");

const db = [Link]("collegeDB");

const students = [Link]("students");

await [Link]({ name: "John", course: "AI", marks: 90 });

const all = await [Link]().toArray();


[Link](" Students from Atlas:", all);

} catch (err) {

[Link](" Connection error:", err);

} finally {

await [Link]();

run();

Step 4: Using .env for Security (Best Practice)

Install dotenv:

npm install dotenv

Create a .env file:

MONGO_URI=mongodb+srv://alex:<password>@[Link]/collegeDB

Now modify your [Link]:

require("dotenv").config();

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

const client = new MongoClient([Link].MONGO_URI);

async function run() {

try {

await [Link]();

[Link](" Connected using .env");

const db = [Link]("collegeDB");

const students = [Link]("students");

await [Link]({ name: "Maya", course: "ML", marks: 95 });

[Link](await [Link]().toArray());

} finally {
await [Link]();

run();

Step 5: Verify Connection

To verify that your database and collection exist:

mongosh

show dbs

use collegeDB

show collections

You should see your students collection with inserted documents.

Simple, real-world applications of MongoDB

MongoDB is popular for web apps, analytics, IoT, and real-time applications because it handles
large, flexible, and fast-changing data easily.

1. Student Management System

Use case: Store and manage student details, courses, and grades.

Example Documents:

name: "Alex",

rollNo: "RA2113003011039",

course: "Soft Computing",

marks: 85,

attendance: 92

Why MongoDB?
• Dynamic schema (different students can have different subjects)

• Easy to query and update student info

2. Employee Management System

Use case: Track employees, departments, and leave details.

Example Documents:

name: "John",

department: "HR",

salary: 50000,

leaves: { casual: 2, medical: 1 }

Operations:

• Add new employees

• Update salary

• Fetch employees by department

• Manage leave records

3. E-commerce Product Catalog

Use case: Store product details and inventory.

Example Documents:

productId: 101,

name: "Nike Air Shoes",

price: 4500,

stock: 25,

category: "Footwear"

}
Why MongoDB?

• Can easily store nested data like reviews, variants, and images.

• Fast search using indexes.

4. Blog or News Application

Use case: Manage posts, authors, and comments.

Example Documents:

title: "What is AI?",

author: "Maya",

tags: ["AI", "Machine Learning"],

content: "Artificial Intelligence is the simulation of human intelligence...",

comments: [

{ user: "John", text: "Nice article!" },

{ user: "Alex", text: "Very informative." }

Why MongoDB?

• Nested comments and tags can be stored inside a single document.

• No need for multiple tables or joins.

5. Banking / Wallet System

Use case: Manage transactions and balances.

Example Documents:

accountNo: 123456,

name: "Priya",

balance: 15000,
transactions: [

{ type: "credit", amount: 5000 },

{ type: "debit", amount: 1000 }

Why MongoDB?

• Fast handling of transaction logs

• Easy to query last 10 transactions

6. Travel or Bus Booking App

Use case: Manage routes, seats, and bookings.

Example Documents:

busNo: "TN45-5678",

from: "Chennai",

to: "Coimbatore",

seatsAvailable: 25,

bookings: [

{ passengerName: "Alex", seatNo: 12 },

{ passengerName: "John", seatNo: 13 }

Why MongoDB?

• Nested booking documents

• Fast update of available seats

7. IoT Sensor Data Storage

Use case: Store live sensor readings (temperature, humidity, etc.)


Example Documents:

sensorId: "T001",

location: "Lab1",

temperature: 32.5,

humidity: 45,

timeStamp: "2025-10-07T10:15:00Z"

Why MongoDB?

• Handles large, time-series data efficiently.

• Ideal for analytics and dashboards.

8. Learning Management System (LMS) (like your project)

Use case: Manage students, courses, assignments, and attendance.

Collections Example:

• students

• courses

• assignments

• attendance

Sample Document:

studentId: "ST123",

name: "Alex",

enrolledCourses: ["Soft Computing", "AI"],

attendance: { SoftComputing: 90, AI: 85 }

Why MongoDB?
• Flexible schema fits various student data.

• Easier to integrate with [Link] backends.

9. Chat Application

Use case: Store messages and user details.

Example Documents:

chatId: 1,

users: ["Alex", "Maya"],

messages: [

{ sender: "Alex", text: "Hi Maya!", time: "2025-10-07T10:00:00Z" },

{ sender: "Maya", text: "Hello Alex!", time: "2025-10-07T10:01:00Z" }

Why MongoDB?

• Ideal for real-time, high-volume message storage.

10. Simple To-do List App

Use case: Store and manage user tasks.

Example Documents:

user: "Alex",

tasks: [

{ title: "Finish MongoDB notes", completed: false },

{ title: "Prepare for exam", completed: true }

]}

Why MongoDB?

• Simple and flexible for dynamic lists.

Common questions

Powered by AI

Transitioning a physical MongoDB instance to a MongoDB Atlas cloud instance involves several key steps: 1) Create an Atlas account and cluster. 2) Ensure the cloud database version is compatible with your local instance. 3) Use the 'mongodump' command to export data from the existing database into BSON files. 4) Transfer the dump files to a location accessible by Atlas, likely via a cloud storage service or through direct upload. 5) Use 'mongorestore' to import the BSON files into Atlas. Adjust the connection string in application configurations to point to the new Atlas instance and test thoroughly for data integrity and application functionality post-migration. This process ensures minimal downtime and seamless transition of data to the cloud environment, capitalizing on Atlas's scalability and management benefits .

MongoDB's flexible schema is advantageous for real-world applications because it allows for the storage of diverse data types without requiring predefined schemas. In a Student Management System, each student might have different information, such as varying courses and grades, which MongoDB can handle seamlessly. Similarly, in an E-commerce Product Catalog, products can have a wide variety of properties, such as multiple categories, attributes, and nested information like reviews and images. The lack of schema enforcement means these systems can evolve without extensive database restructuring, accommodating changing requirements and making it easy to perform updates and queries efficiently .

MongoDB improves the efficiency of managing an IoT sensor data storage application by leveraging its capabilities to handle large-scale, time-series data efficiently. It allows for the rapid insertion and querying of data with its schema-flexible model, supporting variable data types without predefined structures. MongoDB's indexing and search functionalities enhance speed and performance in handling and analyzing live sensor data. Additionally, it supports real-time analytics and dashboard integration, allowing for continuous data insights without compromising on scalability or performance .

To enable and verify MongoDB authentication on Windows, the following steps are taken: 1) Temporarily enable authentication by starting the MongoDB server with the '--auth' option using 'mongod --auth --dbpath C:\data\db'. 2) For permanent authentication, modify the MongoDB configuration file, typically found at 'C:\Program Files\MongoDB\Server\<version>\bin\mongod.cfg' to include 'security: authorization: enabled.' 3) Restart the MongoDB service using 'net stop MongoDB' and 'net start MongoDB' commands to apply changes. To verify, attempt to connect to the MongoDB instance: users must authenticate with credentials to gain access, confirming authentication is enabled .

In MongoDB's Role-Based Access Control system, 'read' role grants a user permission to only view data from a specific database, they cannot modify or delete the data. 'readWrite' role allows a user to both read data and write or modify data in a specific database. The 'root' role is a superuser role that provides full access to all commands and operations across all databases in MongoDB. It includes all permissions from lower-level roles and is typically reserved for administrators who need full management capabilities .

'createUser' and 'grantRolesToUser' are MongoDB commands focused on user and permission management. 'createUser' is used to create a new database user along with initial role assignments, defining the user's access capabilities upon creation. For instance, 'db.createUser({ user: "alex", pwd: "alex123", roles: [ { role: "readWrite", db: "schoolDB" } ] })' creates a user with read and write access to 'schoolDB'. Conversely, 'grantRolesToUser' is used to modify existing user permissions by adding new roles without re-creating the user. This allows for permissions to be updated or expanded post-creation, e.g., 'db.grantRolesToUser("alex", [{ role: "dbAdmin", db: "schoolDB" }])'. These two commands provide flexibility for managing user rights dynamically as application needs evolve .

To create an admin user in MongoDB, follow these commands: 1) Start MongoDB without authentication using 'mongod --dbpath C:\data\db'. 2) Open the MongoDB shell with 'mongosh'. 3) Switch to the 'admin' database using 'use admin'. 4) Create the admin user with 'db.createUser({ user: "adminuser", pwd: "admin123", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] })'. Creating an admin user before enabling authentication is crucial because it establishes a user with sufficient privileges to manage other users and configurations once authentication is active, ensuring secure database operations and access control .

Using MongoDB for an e-commerce product catalog offers several benefits: its flexible schema is ideal for storing diverse product attributes such as multiple categories, and nested documents like reviews and variants, without necessitating structured tables. Its indexing capabilities enhance query efficiency, particularly for complex searches and filtering. However, potential drawbacks include handling transactional consistency across multiple documents, as native MongoDB is optimized for single-document transactions, which can be limiting for applications requiring strict ACID compliance across multiple operations. Careful data modeling and the use of MongoDB's transactions feature can mitigate these drawbacks to some extent .

To configure Node.js to connect securely to a MongoDB Atlas database using environment variables: 1) Install dotenv with 'npm install dotenv'. 2) Create a '.env' file to store the database URI securely, like 'MONGO_URI=mongodb+srv://<username>:<password>@cluster0.mongodb.net/collegeDB'. 3) In your Node.js application, require dotenv and configure it by adding 'require("dotenv").config();' at the beginning of your app. 4) Use the environment variable for MongoDB connection: retrieve the URI in your app.js with 'const client = new MongoClient(process.env.MONGO_URI);'. This approach ensures sensitive information like usernames and passwords remains out of the codebase, facilitating better security .

The PATH environment variable in Windows is critical in defining the directories where executable programs are located. When installing MongoDB, adding the MongoDB bin directory and mongosh to the PATH allows users to execute MongoDB and mongosh commands from any command prompt or PowerShell window without needing to specify the full directory paths. This makes it easier to manage and interact with MongoDB installations by ensuring the relevant executables like mongod and mongosh are accessible globally from the command line .

You might also like