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.