Skip to main content
Advanced Web
Technologies
CSC337
Lecture 7 & 8
Beginning Node.js, Express & MongoDB Development, Lim, G.,
Amazon, 2019.
Lecture 7
MongoDB, Database Creation, Collections, Schemas, and its
Access with Aggregate Functions. Greg : Ch 8,9
What is MongoDB?
• MongoDB is a NoSQL database (document-oriented).
• Stores data in JSON-like documents (called BSON — Binary
JSON).
• Flexible schema .
• Very scalable, widely used in real-world apps.
• Schema = the structure/rules for documents.
• MongoDB default = schema-less (flexible).
Why you would used MongoDB?
I would use MongoDB in projects where data is dynamic,
scalability is required, and I am working with a JavaScript-
based stack.
However, I would avoid MongoDB in systems that require
complex joins, strict relational integrity, and heavy
transactional consistency like banking systems.
Architecture Mode Best For
Standalone Dev/Test, small apps
Replica Set
Production, high
availability
Sharding
Large-scale, high-volume
apps
Cloud Atlas
Quick deployment,
managed service, global
access
Question Answer
What is replication?
Copying data across multiple servers for
redundancy and high availability.
What is a replica
set?
Group of MongoDB servers with one Primary
(writes) and multiple Secondaries
(reads/backup).
What is sharding?
Horizontal scaling; distributes data across
multiple servers using a shard key.
Horizontal add more servers.
→
Vertical upgrade a single server’s
→
CPU/RAM/storage.
Default port of MongoDB:
27017
MongoDB Download link
https://www.mongodb.com/try/download/community
Video Tutorial Guide for
Installation
https://www.youtube.com/watch?v=IW8ptYqX_6k
Key Terms in MongoDB
Database
• A container for collections.
• Equivalent to a database in SQL.
• One MongoDB server can have multiple databases.
Example
use schoolDB
Collection
• A group of documents.
• Equivalent to a table in SQL.
• Does not enforce a schema (but you can use schema
validation).
Example
db.createCollection("students")
Document
• The basic unit of data in MongoDB.
• Stored as BSON (Binary JSON), but looks like JSON.
• Equivalent to a row in SQL.
Example:
{ "name": "Alice", "age": 22, "major": "CS" }
Field
• A key–value pair inside a document.
• Equivalent to a column in SQL.
{ "name": "Bob", "age": 20 }
// Here, "name" and "age" are fields.
_id
• A unique identifier for every document (primary key).
• Automatically generated if not provided.
• Usually an ObjectId (12-byte unique value).
Example
{ "_id": ObjectId("64f28d1..."), "name": "Charlie" }
BSON (Binary JSON)
• Internal storage format of MongoDB.
• Supports extra data types (like Date, Decimal128) beyond
JSON.
MQL (MongoDB Query Language)
• The language used to interact with MongoDB.
• Syntax is JSON-like.
Example:
db.students.find({ age: { $gt: 20 } })
CRUD Operations
• Create insertOne(), insertMany()
→
• Read find(), findOne()
→
• Update updateOne(), updateMany()
→
• Delete deleteOne(), deleteMany()
→
Index
• A special data structure to speed up queries.
• Works like an index in a book (quick lookup).
Example:
db.students.createIndex({ name: 1 })
Aggregation
• A framework for advanced data processing (like SQL’s
GROUP BY, JOIN, HAVING).
• Uses pipeline stages ($match, $group, $project, $sort,
$lookup).
Example:
db.students.aggregate([
{ $group: { _id: "$major", avgAge: { $avg: "$age" } } }
])
Pipeline
• A sequence of stages in aggregation.
• Each stage transforms the data and passes it to the next.
• Order of stages (always remember MGPSL):
MATCH GROUP PROJECT SORT LIMIT
→ → → →
$ Operators
• Special keywords used in queries/aggregation.
• Example categories:
• Comparison operators: $eq, $gt, $lt
• Logical operators: $and, $or, $not
• Update operators: $set, $inc, $push
Example
db.students.updateOne({ name: "Alice" }, { $inc: { age: 1 } })
University Management System with
MongoDB (Problem Statement)
• The university wants to build a database system to manage
students, teachers, and courses. The system should:
• Store details of students and teachers.
• Allow inserting, updating, and deleting records.
• Validate teacher records using schema rules.
• Generate reports using aggregation queries.
• You are hired as a MongoDB developer. Implement the
system step by step
Step 1: Create Database
use universityDB
• This creates the universityDB database
Step 2: Create Collections
• db.createCollection("students")
• db.createCollection("teachers")
• db.createCollection("courses")
Step 3: Insert Student Records
db.students.insertMany([
{ name: "Alice", age: 22, major: "CS", gpa: 3.5 },
{ name: "Bob", age: 20, major: "Math", gpa: 3.2 },
{ name: "Charlie", age: 21, major: "Physics", gpa: 3.7 },
{ name: "David", age: 23, major: "CS", gpa: 3.8 }
])
Step 4: Insert Teacher Records (with
Schema Validation)
db.createCollection("teachers", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["name", "subject", "age"],
properties: {
name: { bsonType: "string" },
subject: { bsonType: "string" },
age: { bsonType: "int", minimum: 25 }
}
}
}
})
Insert valid teacher documents:
db.teachers.insertMany([
{ name: "Dr. Smith", subject: "CS", age: 45 },
{ name: "Dr. Johnson", subject: "Math", age: 38 }
])
Step 5: Insert Courses
db.courses.insertMany([
{ title: "Database Systems", credits: 4, department: "CS" },
{ title: "Linear Algebra", credits: 3, department: "Math" },
{ title: "Quantum Mechanics", credits: 4, department:
"Physics" }
])
Step 6: Basic Queries (CRUD)
• Find all students:
db.students.find()
• Find students older than 21:
db.students.find({ age: { $gt: 21 } })
• Update GPA of Alice:
db.students.updateOne(
{ name: "Alice" },
{ $set: { gpa: 3.9 } }
)
Step 6: Basic Queries (CRUD)(CONT..)
• Delete a student:
db.students.deleteOne({ name: "Charlie" })
Step 7: Aggregation Queries
• Count students by major:
db.students.aggregate([
{ $group: { _id: "$major", totalStudents: { $sum: 1 } } }
])
• Average GPA per major:
db.students.aggregate([
{ $group: { _id: "$major", avgGPA: { $avg: "$gpa" } } }
])
Find top 2 students with highest GPA:
db.students.aggregate([
{ $sort: { gpa: -1 } },
{ $limit: 2 }
])
Ecommerce
database Inserting documents
into
Customers(Collection)
Inserting documents
into Products(Collection)
Insert Orders
Show all
customers
Show all
customers
Find
customers
age > 25
Update
stock of
Laptop
from 9
to 15
After
updation
Increase
price of
all
Electronics
by 5000
(Before)
After
Updation
Delete customers age < 23
Find customers from Lahore AND age > 26
Find products price between 5000 and 60000
Find customers from Lahore OR Karachi
Sort products by price descending
Show only name and
city of customers
Count total products,
customers and orders
Name starts with A
Query Meaning
{stock: 0}
Find documents
where stock is
exactly 0
{stock:
{$exists:true}}
Find documents
where stock field
exists (any value)
{stock:
{$exists:false}}
Find documents
where stock field
does NOT exist
Products where stock exists
Total sales
Average product price per category
Top spending customer
Add discount field (10% if total > 50000)
Join orders with customers
Lookup works as left outer join
Documents with
age < 23 were
deleted
Join orders with customers
(Output)
Join orders with products
Create index on product name
Drop index on product name
Lecture 8
Implementation of MongoDB Client Connector with Node.JS
(Mongo Client). Greg : Ch 10
What is MongoClient?
• MongoClient is the official MongoDB driver for Node.js.
• It allows your Node.js application to connect to a MongoDB
database, run queries, and perform CRUD + Aggregation
operations.
• Think of it as the “bridge” between your Node.js code and
the MongoDB server.
Setup
Step 1: Install MongoDB Driver
Run this in your Node.js project folder:
• npm init -y
• npm install mongodb
Step 2: Basic Project Structure
• project/
• ├── index.js
• ├── package.json
3. Connect to MongoDB(Code: index.js)
const { MongoClient } = require("mongodb");
// Connection URL (local MongoDB)
const url = "mongodb://127.0.0.1:27017";
const client = new MongoClient(url);
// Database name
const dbName = "universityDB";
3. Connect to MongoDB(Code:
index.js)CONT
async function main() {
try {
// Connect the client
await client.connect();
console.log("Connected to MongoDB");
const db = client.db(dbName);
const students = db.collection("students");
// Insert a document
const result = await students.insertOne({ name:
"Alice", age: 22, major: "CS" });
console.log("Inserted ID:", result.insertedId);
// Find documents
const allStudents = await students.find().toArray();
console.log("Students:", allStudents);
} catch (err) {
console.error("❌ Error:", err);
} finally {
// Close connection
await client.close();
console.log(" Connection closed");
🔒
}
}
main();
readline module
• Built-in Node.js module that allows you to read input from
the user via the command line (terminal/console) and
write output to it.
• commonly used for interactive CLI programs, like menus,
prompts
• don’t need to install anything—it comes with Node.js.
Key Features of readline
• Read input line by line.
• Prompt users for input.
• Create interactive command-line interfaces.
• Can be used with streams, like process.stdin (keyboard
input) and process.stdout (console output).
Creating a Menu with readline
Lecture 7_8  advanced web technologies ppt