Lecture 7
MongoDB, DatabaseCreation, Collections, Schemas, and its
Access with Aggregate Functions. Greg : Ch 8,9
3.
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).
4.
Why you wouldused 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.
6.
Architecture Mode BestFor
Standalone Dev/Test, small apps
Replica Set
Production, high
availability
Sharding
Large-scale, high-volume
apps
Cloud Atlas
Quick deployment,
managed service, global
access
8.
Question Answer
What isreplication?
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.
Database
• A containerfor collections.
• Equivalent to a database in SQL.
• One MongoDB server can have multiple databases.
Example
use schoolDB
14.
Collection
• A groupof documents.
• Equivalent to a table in SQL.
• Does not enforce a schema (but you can use schema
validation).
Example
db.createCollection("students")
15.
Document
• The basicunit 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" }
16.
Field
• A key–valuepair inside a document.
• Equivalent to a column in SQL.
{ "name": "Bob", "age": 20 }
// Here, "name" and "age" are fields.
17.
_id
• A uniqueidentifier for every document (primary key).
• Automatically generated if not provided.
• Usually an ObjectId (12-byte unique value).
Example
{ "_id": ObjectId("64f28d1..."), "name": "Charlie" }
18.
BSON (Binary JSON)
•Internal storage format of MongoDB.
• Supports extra data types (like Date, Decimal128) beyond
JSON.
19.
MQL (MongoDB QueryLanguage)
• The language used to interact with MongoDB.
• Syntax is JSON-like.
Example:
db.students.find({ age: { $gt: 20 } })
Pipeline
• A sequenceof 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
→ → → →
24.
$ Operators
• Specialkeywords 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 } })
25.
University Management Systemwith
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
26.
Step 1: CreateDatabase
use universityDB
• This creates the universityDB database
Query Meaning
{stock: 0}
Finddocuments
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
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.
3. Connect toMongoDB(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();
69.
readline module
• Built-inNode.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.
70.
Key Features ofreadline
• 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).