MongoDB, Modularization and
Webpack
Module 5
CS380
⚛️MongoDB Basics
2
MongoDB is a document-oriented
database.
It stores data as documents, not
rows/columns like SQL.
A group of documents is called a
collection.
We'll explore using the mongo shell to
CS380
📄 What is a Document?
3
A document is like a record, but in JSON-
like format.
Made up of field-value pairs.
Fields can store:
Simple values (e.g., strings, numbers,
booleans)
Embedded documents (nested objects)
Arrays of documents
CS380
Example: Person Document
4
{
"name": “Suki",
"age": 30,
"gender": "Male",
"email": “Suki@[Link]",
}
CS380
Example: Person Document
5
{
"name": “Suki",
"age": 30,
"gender": "Male",
},
{
"name": “Pari",
"age": 28,
"gender": "Female",
"email": “pari@[Link]",
}
CS380
📂 MongoDB Collections
6
🔸 What is a Collection?
A collection is similar to a table in SQL.
It stores a set of documents.
You access documents via the collection.
CS380
🔑 Primary Key in MongoDB
7
Every document must have a primary
key called _id.
If not provided, MongoDB auto-
generates it.
Auto-generated _id is of type ObjectId.
Ensures uniqueness even during
simultaneous writes.
CS380
📌 Indexes
8
The _id field is automatically indexed.
You can create custom indexes on:
Regular fields
Fields inside embedded documents
Array fields
CS380
📐 Schema Flexibility
9
No fixed schema is required.
Only _id is mandatory and must be
unique.
Documents in a collection can have
different structures.
⚠️However, using flexible schema
carelessly can lead to data inconsistency.
CS380
🔍 MongoDB Query
10
Language
1. Method-Based, Not SQL
MongoDB uses methods instead of SQL.
No English-like queries (e.g., SELECT *
FROM…).
Uses CRUD methods:
insert(), find(), update(), delete()
Other operations:
Aggregation, text search, geospatial
queries
CS380
📄 2. Query Format
11
Queries operate on collections only.
Parameters are passed as JavaScript-like
objects.
Example:
[Link]({ gender: "male" },
{ name: 1, age: 1 })
CS380
🔁 3. No Multi-Collection Operations
12
MongoDB does not support joins.
One method works on one collection at a
time.
To combine data:
Query each collection separately
CS380
📦 4. Denormalization
13
MongoDB encourages embedding data
(denormalization).
Example:
Relational DB: Separate People and
Contacts tables + join.
MongoDB: Embed Contacts inside each
People document.
CS380
⚙️MongoDB Installation
14
💻 1. Supported Operating Systems
Works on Windows, macOS, and Linux.
Follow official steps here:
[Link]
installation/
CS380
⬇️2. Download & Version
15
Choose version 3.2 or higher (preferably
latest).
Installer usually includes:
MongoDB Server
Mongo Shell
Tools
Some OS setups may need manual tool
installation.
CS380
🚀 3 Ways to Install
16
MongoDB
1️⃣MongoDB Community Server
(Offline Installation)
2️⃣MongoDB Extension for Visual
Studio
3️⃣MongoDB Atlas (Cloud-Based)
CS380
🧪 4. Test the Installation
17
Open the mongo shell:
mongo
On Windows: use [Link]
Use path if not added to system variables.
Expected Output:
MongoDB shell version: 3.2.4
connecting to: test
>
CS380
Creating Database in
18
MongoDB
✅ 1. Creating a Database
🔹 Step-by-step:
use myDatabase
Switches to myDatabase
If it doesn’t exist, it will be created when
you insert data
use school
[Link]({ name: "Asha",
age: 21 })
CS380
2. Dropping a Database
19
🔹 Command:
[Link]()
Deletes the current database you are
connected to
Must run after use myDatabase
use school
[Link]()
CS380
🔄 Switching Between
20
Databases
use school // switches to "school"
database
use library // switches to "library"
database
CS380
Insert a Document:
21
Use the insertOne() method to insert a
single document into a collection. If the
collection doesn't exist, MongoDB will
create it automatically.
Insert a Single Document:
[Link]({
name: "Aarav",
age: 25,
CS380city: "Mumbai"
Insert Multiple Documents:
22
db. [Link]([
{ name: "Alice", age: 28, city: "London"
},
{ name: "Bob", age: 35, city: "Paris" }
])
CS380
Update Methods:
23
1. updateOne()
Update a single document where name
is "Aarav":
[Link](
{ name: "Aarav" }, // Filter
{ $set: { city: "Pune" } } // Update
)
If Aarav already has a city field, it will be
updated to "Pune".
If Aarav does not have a city field,
CS380
MongoDB will add it with the value
Without $set
24
[Link](
{ name: "Aarav" },
{ city: "Pune" } // ❌ This replaces the
whole document
)
CS380
2. updateMany()
25
Update all documents where city is
"Mumbai":
[Link](
{ city: "Mumbai" }, // Filter
{ $set: { city: "Delhi" } } // Update
)
CS380
3. replaceOne()
26
Replace entire document where name is
"Aarav":
[Link](
{ name: "Aarav" }, // Filter
{ name: "Aarav", age: 26, city: "Kolkata" }
// New
Document
)
CS380
DELETE DOCUMENTS
27
1. Using MongoDB Shell
✅ Delete One Document:
Deletes the first document that matches
the filter.
[Link]({ name: "Aarav" })
CS380
28
✅ Delete Many Documents:
Deletes all documents that match the
filter.
[Link]({ city: "Delhi" })
✅ Delete All Documents:
Deletes all documents in the collection
(but keeps the collection).
[Link]({})
CS380
🐚 To delete a collection
29
use myDatabase # Switch to your
database
[Link]()
✅ This will:
Permanently delete the entire students
collection
Remove all documents inside it
The collection will no longer exist
CS380
👀 View Collections in a
30
Database
List all collections:
show collections
📄 View Documents in a Collection
To see all documents in a collection
called students:
[Link]()
This shows all documents in the
collection.
CS380
🔹 [Link]()
31
Returns all documents in the students
collection in compact JSON format.
🔸 Example Output:
{ "_id" : ObjectId("661ffabc123..."), "name" : "Aarav", "city"
: "Pune" }
{ "_id" : ObjectId("661ffacb456..."), "name" : "Meera",
"city" : "Delhi" }
✅ Quick and minimal, but hard to read
when documents are long.
CS380
🔹 [Link]().pretty()
32
Returns the same documents, but nicely
formatted (indented) for better
readability.
🔸 Example Output:
{
"_id" : ObjectId("661ffabc123..."),
"name" : "Aarav",
"city" : "Pune"
}
{
"_id" : ObjectId("661ffacb456..."),
"name" : "Meera",
CS380
"city" : "Delhi"
🔍 Filtered View:
33
Get documents where city is "Mumbai":
[Link]({ city: "Mumbai" })
[Link]({ city: "Mumbai", name:
"Ravi" })
CS380
📌 Projection in MongoDB
34
Definition:
Projection is used to select specific fields
from documents, rather than retrieving the
entire document.
Purpose:
Improve performance by fetching only
needed fields.
Syntax:
[Link](query, projection)
Use 1 to include, and 0 to exclude fields.
CS380
(Note: You can’t mix 1 and 0 in the same
✅ Example Collection
35
(students):
{
"_id": ObjectId("..."),
"name": "Aarav",
"city": "Pune",
"marks": 85
}
CS380
🔹 Example 1: Show only name and
city
36
[Link]({}, { name: 1, city: 1,
_id: 0 })
🟢 Output:
{ "name": "Aarav", "city": "Pune" }
CS380
🔹 Example 2: Exclude city
37
[Link]({}, { city: 0 })
🟢 Output:
{ "_id": "...", "name": "Aarav", "marks":
85 }
CS380
✅ Final Summary:
38
find({ ... }) = Filter = Which documents
find({}, { ... }) = Projection = Which
fields
CS380
📌Aggregation in MongoDB?
39
Definition:
Aggregation is a powerful way to process
and transform data in MongoDB — like
grouping, filtering, sorting, or calculating
totals.
Purpose:
Similar to GROUP BY, SUM, COUNT in SQL.
Uses:
Total marks per student
Number of students per city
Average score
CS380
40
Filter + group + sort in one go
Command:
[Link]([ .. $group... ])
CS380
🔹 Example Collection
41
(students)
{ "name": "Aarav", "city": "Pune", "marks": 85 }
{ "name": "Meera", "city": "Mumbai", "marks": 92
}
{ "name": "Kabir", "city": "Pune", "marks": 78 }
🔹 Example Aggregation: Count students
by city
[Link]([
{ $group: { _id: "$city", count: { $sum:
1}}}
])
CS380
🟢 Output:
🔍 MongoDB is Schema-less
42
(Flexible)
By default, you can insert any shape of
data:
{ "name": "Alice", "age": 25 }
{ "username": "bob123", "hobbies": ["reading",
"games"] }
No strict rules — it accepts any
structure.
CS380
🤔 Then Why Use Schema?
43
Because Mongoose (a popular ODM – Object Data
Modeling library) adds structure on top of
MongoDB for these benefits:
✅ Reasons to Use Schema with Mongoose
Benefit Why it matters
🔐 Validation Ensures only correct data is stored (e.g.,
name must be String).
📋 Default Values Automatically adds fields like
createdAt, isActive, etc.
🧠 Business Logic Add custom functions/methods
inside schema.
🔄 Consistency Keeps all documents in a collection similar
— easier to query.
CS380
⚠️Error Checking Detects and avoids
📌 Example Without Schema (using native
MongoDB)
44
You might accidentally store:
{ "name": "Alice", "age": "twenty-five" }
❌
{ "name": "Bob" } ⚠️
missing age
Hard to handle later in code.
CS380
✅ With Schema (using
45
Mongoose)
const studentSchema = new [Link]({
name: { type: String, required: true },
age: { type: Number, required: true }
});
Now if someone tries:
{ "name": "Bob" }
Mongoose will reject it because age is required.
📘 Summary:
MongoDB is schema-less ➝ great flexibility
Mongoose uses schemas ➝ better control, validation, and
developer sanity
CS380
Modularization and
46
Webpack
The code is split into multiple files
instead of one big file.
The server will automatically restart
when any file changes.
The browser will auto-refresh during
development.
We can add checks to catch mistakes
CS380
🧩 What is a module?
47
A module is just a file that contains some
code.
If you want to reuse code from one file in
another, you use:
[Link] → to share the code.
require() → to use the shared code.
CS380
🔄 Auto-Restart with
nodemon
48
To make nodemon watch the entire
server folder, we change the start
command:
Old:
"start": "nodemon -w [Link] [Link]"
New:
"start": "nodemon -w server
server/[Link]"
Now nodemon will restart the server if
any file in the server folder changes.
CS380
💡 What is Webpack?
49
Webpack is a tool (also called a bundler)
used in web development to:
Bundle your JavaScript files (combine
many files into one).
Convert modern code (like ES6, JSX,
SCSS) into browser-friendly code.
Auto-refresh your browser when you
change files.
Optimize your app for faster loading.
CS380
🧠 Why do we need
50
Webpack?
Let’s say your app has:
[Link]
[Link]
[Link]
[Link]
Maybe React, Vue, or other libraries
Without Webpack:
You’d manually link all files., etc.
CS380
51
With Webpack:
You write modular code, and Webpack
bundles it into one optimized file.
It handles converting, watching, refreshing
CS380
What does Webpack do?
52
Task What Webpack Does
Combine files Turns many .js files into
one file
(bundle)
Transpile code Converts modern JS/React
code to
browser-safe code using
loaders
Live Reload Refreshes browser when
code
CS380
53
CS380
54
CS380
55
CS380
56
CS380
57
CS380
58
CS380
59
CS380
60
CS380
61
CS380
62
CS380