Assignment No-1
Aim: Identification of Project, Draw E-R Diagram and Convert Entities and Relationships to
Relations
Objective:
To understand and apply the concepts of Entity-Relationship (E-R) modelling and convert the
model into relational schema.
PART 1: IDENTIFICATION OF PROJECT
Project Title:
Online Food Ordering Management System
Project Description:
The Online Food Ordering Management System allows customers to browse food items,
place orders, and make payments online. The system maintains details about customers,
restaurants, food items, orders, and payments.
📊 PART 2: E-R DIAGRAM
Entities and Attributes:
1. Customer
o Customer_ID (PK)
o Name
o Email
o Phone
o Address
2. Restaurant
o Restaurant_ID (PK)
o Name
o Location
o Contact_Number
3. Food_Item
o Food_ID (PK)
o Name
o Price
o Category
o Restaurant_ID (FK)
4. Order
o Order_ID (PK)
o Order_Date
o Status
o Customer_ID (FK)
5. Order_Details (associative entity for M:N relation between Order and Food_Item)
o Order_ID (PK, FK)
o Food_ID (PK, FK)
o Quantity
6. Payment
o Payment_ID (PK)
o Order_ID (FK)
o Payment_Date
o Amount
o Payment_Mode
📊 E-R Diagram Description
📊 PART 3: CONVERSION TO RELATIONAL SCHEMA
Customer(
Customer_ID PRIMARY KEY,
Name,
Email,
Phone,
Address
)
Restaurant(
Restaurant_ID PRIMARY KEY,
Name,
Location,
Contact_Number
)
Food_Item(
Food_ID PRIMARY KEY,
Name,
Price,
Category,
Restaurant_ID FOREIGN KEY REFERENCES Restaurant(Restaurant_ID)
)
Order(
Order_ID PRIMARY KEY,
Order_Date,
Status,
Customer_ID FOREIGN KEY REFERENCES Customer(Customer_ID)
)
Order_Details(
Order_ID FOREIGN KEY REFERENCES Order(Order_ID),
Food_ID FOREIGN KEY REFERENCES Food_Item(Food_ID),
Quantity,
PRIMARY KEY(Order_ID, Food_ID)
)
Payment(
Payment_ID PRIMARY KEY,
Order_ID FOREIGN KEY REFERENCES Order(Order_ID),
Payment_Date,
Amount,
Payment_Mode
)
Conclusion:
In this assignment, we identified a real-world project (Food Ordering System), created its E-
R diagram, and successfully converted the entities and relationships into relational schema.
Assignment -2
Aim: To perform the following SQL activities on a project:
1. Creating a database
2. Creating tables (with keys and constraints)
3. Inserting records into tables
📊 Tools/Software Required:
MySQL / PostgreSQL / Oracle / MS SQL Server
SQL Editor or Command Line
Any RDBMS-compatible tool (e.g., MySQL Workbench, DBeaver, pgAdmin)
Theory:
Structured Query Language (SQL) is used to communicate with a database. The key SQL
components used in this lab are:
CREATE DATABASE: Used to create a new database.
CREATE TABLE: Used to define the structure of tables including primary/foreign
keys and constraints.
INSERT INTO: Used to insert data into tables.
📊 Project Scenario:
Assume a simple Student Course Enrollment System with the following entities:
1. Students
2. Courses
3. Enrollments
A. Creating a Database
CREATE DATABASE StudentEnrollmentDB;
USE StudentEnrollmentDB;
B. Creating Tables (With Keys and Constraints)
Students Table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50) NOT NULL,
LastName VARCHAR(50),
Email VARCHAR(100) UNIQUE,
DOB DATE
);
Courses Table
CREATE TABLE Courses (
CourseID INT PRIMARY KEY,
CourseName VARCHAR(100) NOT NULL,
Credits INT CHECK (Credits BETWEEN 1 AND 5)
);
Enrollments Table
CREATE TABLE Enrollments (
EnrollmentID INT PRIMARY KEY,
StudentID INT,
CourseID INT,
EnrollmentDate DATE,
FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);
C. Inserting Records in Tables
Insert Students
INSERT INTO Students VALUES (1, 'John', 'Doe', '[email protected]', '2000-03-10');
INSERT INTO Students VALUES (2, 'Jane', 'Smith', '[email protected]', '2001-07-
22');
Insert Courses
INSERT INTO Courses VALUES (101, 'Database Systems', 4);
INSERT INTO Courses VALUES (102, 'Operating Systems', 3);
Insert Enrollments
INSERT INTO Enrollments VALUES (1001, 1, 101, '2024-06-15');
INSERT INTO Enrollments VALUES (1002, 2, 102, '2024-06-16');
Conclusion:
The SQL activities such as creating a database, defining tables with keys and constraints, and
inserting records were successfully performed using SQL queries.
Assignment-3
Objective: To perform the following SQL activities:
1. Viewing all databases
2. Viewing all tables in a database
3. Updating and deleting records in a table
4. Altering a table
5. Dropping, truncating, and renaming tables
Tools/Software Required:
MySQL / PostgreSQL / Oracle / MS SQL Server
SQL Editor or CLI
MySQL Workbench / pgAdmin / DBeaver (optional GUI)
Theory:
SQL provides various Data Definition Language (DDL) and Data Manipulation Language
(DML) commands for managing databases and tables:
SHOW DATABASES, SHOW TABLES are used to view available databases and
tables.
UPDATE, DELETE modify existing data in tables.
ALTER TABLE is used to change the structure of a table.
DROP, TRUNCATE, and RENAME affect the table’s existence or content.
SQL Queries:
1. Viewing All Databases
SHOW DATABASES;
2. Viewing All Tables in a Database
USE StudentEnrollmentDB; -- or your database name
SHOW TABLES;
3. Updating Records in a Table
-- Update a student's email
UPDATE Students
SET Email = '
[email protected]'
WHERE StudentID = 1;
4. Deleting Records from a Table
-- Delete a specific course
DELETE FROM Courses
WHERE CourseID = 102;
5. Altering a Table
-- Add a new column to Students table
ALTER TABLE Students
ADD PhoneNumber VARCHAR(15);
-- Modify the column type
ALTER TABLE Students
MODIFY Email VARCHAR(150);
-- Drop a column
ALTER TABLE Students
DROP COLUMN PhoneNumber;
6. Dropping a Table
DROP TABLE Enrollments;
7. Truncating a Table (Delete all records, but keep the structure)
TRUNCATE TABLE Courses;
8. Renaming a Table
RENAME TABLE Students TO StudentDetails;
Expected Output:
List of databases
List of tables in selected database
Modified records as per update/delete commands
Table structure altered as expected
Tables dropped/truncated/renamed
Precautions:
Always back up data before using DELETE, TRUNCATE, or DROP.
Confirm table names and conditions in WHERE clauses to avoid data loss.
Conclusion:
The experiment successfully demonstrated viewing database structures and performing
common table operations using SQL.
Assignment No-4
Objective: To perform the following SQL queries
1. Simple Queries with Aggregate Functions
2. Aggregate Functions with GROUP BY
3. HAVING Clause
4. ORDER BY Clause
SQL Queries with Aggregate Functions
📊 Database: CollegeDB
📊 Table: Students
StudentID Name Department Age Marks
1 Alice CSE 20 85
2 Bob CSE 22 78
3 Charlie ECE 21 92
4 David ECE 23 88
5 Eva IT 20 76
6 Frank IT 22 89
7 Grace CSE 21 91
1. Simple Queries with Aggregate Functions
Aggregate Functions: COUNT(), SUM(), AVG(), MIN(), MAX()
Example 1: Count total students
SELECT COUNT(*) AS Total_Students FROM Students;
Example 2: Find average marks
SELECT AVG(Marks) AS Average_Marks FROM Students;
Example 3: Find highest marks
SELECT MAX(Marks) AS Highest_Marks FROM Students;
2. Queries with Aggregate Functions + GROUP BY
GROUP BY: Used to group rows with the same values into summary rows.
Example 4: Count students in each department
SELECT Department, COUNT(*) AS Student_Count
FROM Students
GROUP BY Department;
Example 5: Average marks in each department
SELECT Department, AVG(Marks) AS Average_Marks
FROM Students
GROUP BY Department;
3. Queries using HAVING Clause
HAVING: Used to filter records after grouping (like WHERE but for groups).
Example 6: Departments with more than 2 students
SELECT Department, COUNT(*) AS Student_Count
FROM Students
GROUP BY Department
HAVING COUNT(*) > 2;
Example 7: Departments with average marks above 80
SELECT Department, AVG(Marks) AS Avg_Marks
FROM Students
GROUP BY Department
HAVING AVG(Marks) > 80;
4. Queries with ORDER BY Clause
ORDER BY: Sort the result-set by one or more columns.
Example 8: Display all students sorted by marks (descending)
SELECT * FROM Students
ORDER BY Marks DESC;
Example 9: Show departments with average marks, sorted ascending
SELECT Department, AVG(Marks) AS Avg_Marks
FROM Students
GROUP BY Department
ORDER BY Avg_Marks ASC;
Practice Tasks
1. Find the student with the lowest marks.
2. Show the number of students aged 21 or older in each department.
3. List departments where the highest marks exceed 90.
4. Display students ordered by department and then by marks descending.
Conclusion:
The experiment successfully demonstrated viewing database structures and performing SQL
queries.
Assignment -5
Aim:
To perform SQL queries demonstrating different types of Join operations:
Inner Join
Left Join
Right Join
Full Outer Join
Software/Tools Required:
MySQL / SQL Server / PostgreSQL
SQL client (e.g., MySQL Workbench, pgAdmin, SSMS) or Online SQL Editor
Database Schema:
Create the following two tables for demonstration:
CREATE TABLE Students (
student_id INT PRIMARY KEY,
student_name VARCHAR(50),
course_id INT
);
CREATE TABLE Courses (
course_id INT PRIMARY KEY,
course_name VARCHAR(50)
);
Insert Sample Data:
INSERT INTO Students (student_id, student_name, course_id) VALUES
(1, 'Alice', 101),
(2, 'Bob', 102),
(3, 'Charlie', 103),
(4, 'Daisy', NULL);
INSERT INTO Courses (course_id, course_name) VALUES
(101, 'Computer Science'),
(102, 'Information Systems'),
(104, 'Mechanical Engineering');
1. Inner Join
Query:
SELECT Students.student_name, Courses.course_name
FROM Students
INNER JOIN Courses ON Students.course_id = Courses.course_id;
Explanation:
Returns only students who are enrolled in a course that exists in the Courses table.
2. Left Join
Query:
SELECT Students.student_name, Courses.course_name
FROM Students
LEFT JOIN Courses ON Students.course_id = Courses.course_id;
Explanation:
Returns all students, with their course name if available. Shows NULL for students not
enrolled in any course.
3. Right Join
Query:
SELECT Students.student_name, Courses.course_name
FROM Students
RIGHT JOIN Courses ON Students.course_id = Courses.course_id;
Explanation:
Returns all courses, and the student name if any student is enrolled. Shows NULL for courses
not taken by any student.
4. Full Outer Join (Note: Not supported in MySQL directly)
Query (in PostgreSQL or SQL Server):
SELECT Students.student_name, Courses.course_name
FROM Students
FULL OUTER JOIN Courses ON Students.course_id = Courses.course_id;
Alternative in MySQL using UNION:
SELECT Students.student_name, Courses.course_name
FROM Students
LEFT JOIN Courses ON Students.course_id = Courses.course_id
UNION
SELECT Students.student_name, Courses.course_name
FROM Students
RIGHT JOIN Courses ON Students.course_id = Courses.course_id;
Explanation:
Returns all students and all courses, showing NULL where no match is found.
Conclusion:
This experiment demonstrates how different types of JOIN operations work in SQL to
combine data from multiple tables based on related columns.
Assignment N0-6
Aim:
To perform SQL queries that demonstrate the use of Subqueries, including:
Subqueries
Subqueries with IN
Subqueries with EXISTS
Subqueries with ANY / ALL
Software/Tools Required:
MySQL / PostgreSQL / SQL Server
SQL client (Workbench, pgAdmin, SSMS, etc.) or Online SQL Editor
Database Schema:
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
salary INT,
department_id INT
);
CREATE TABLE Departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);
Insert Sample Data:
INSERT INTO Departments (department_id, department_name) VALUES
(1, 'HR'),
(2, 'IT'),
(3, 'Sales');
INSERT INTO Employees (emp_id, emp_name, salary, department_id) VALUES
(101, 'Alice', 50000, 1),
(102, 'Bob', 60000, 2),
(103, 'Charlie', 55000, 2),
(104, 'Daisy', 40000, 1),
(105, 'Eve', 70000, 3);
1. Simple Subquery
Query:
SELECT emp_name, salary
FROM Employees
WHERE salary > (SELECT AVG(salary) FROM Employees);
Explanation:
Lists employees earning more than the average salary.
2. Subquery with IN
Query:
SELECT emp_name
FROM Employees
WHERE department_id IN (
SELECT department_id FROM Departments WHERE department_name = 'IT'
);
Explanation:
Returns names of employees who work in the IT department.
3. Subquery with EXISTS
Query:
SELECT department_name
FROM Departments d
WHERE EXISTS (
SELECT * FROM Employees e WHERE e.department_id = d.department_id
);
Explanation:
Returns names of departments that have at least one employee.
4. Subquery with ANY
Query:
SELECT emp_name, salary
FROM Employees
WHERE salary > ANY (
SELECT salary FROM Employees WHERE department_id = 1
);
Explanation:
Returns employees whose salary is greater than any employee in the HR department.
5. Subquery with ALL
Query:
SELECT emp_name, salary
FROM Employees
WHERE salary > ALL (
SELECT salary FROM Employees WHERE department_id = 1
);
Explanation:
Returns employees whose salary is greater than all employees in the HR department.
Conclusion:
This experiment demonstrates how subqueries are used in SQL to filter data using nested
SELECT statements, including conditional clauses like IN, EXISTS, ANY, and ALL.
Assignment N0-7
Aim:
To demonstrate the creation and use of Views in SQL and perform various operations such
as:
Creating a View
Querying a View
Updating Data through a View
Dropping a View
Software/Tools Required:
MySQL / PostgreSQL / SQL Server
SQL Client (MySQL Workbench, pgAdmin, SSMS) or Online SQL Editor
Database Schema:
CREATE TABLE Employees (
emp_id INT PRIMARY KEY,
emp_name VARCHAR(50),
salary INT,
department_id INT
);
CREATE TABLE Departments (
department_id INT PRIMARY KEY,
department_name VARCHAR(50)
);
Insert Sample Data:
INSERT INTO Departments (department_id, department_name) VALUES
(1, 'HR'),
(2, 'IT'),
(3, 'Finance');
INSERT INTO Employees (emp_id, emp_name, salary, department_id) VALUES
(101, 'Alice', 50000, 1),
(102, 'Bob', 60000, 2),
(103, 'Charlie', 70000, 2),
(104, 'Daisy', 45000, 3),
(105, 'Eve', 40000, 1);
1. Creating a View
Query:
CREATE VIEW HighSalaryEmployees AS
SELECT emp_name, salary
FROM Employees
WHERE salary > 50000;
Explanation:
This view shows the names and salaries of employees earning more than 50,000.
2. Querying a View
Query:
SELECT * FROM HighSalaryEmployees;
Explanation:
Retrieves data from the created view just like a regular table.
3. Updating Data through a View
(Note: Only possible if the view is updatable and doesn't contain joins, aggregates, etc.)
Query:
CREATE VIEW SimpleEmployeeView AS
SELECT emp_id, emp_name, salary
FROM Employees;
-- Now update salary via the view
UPDATE SimpleEmployeeView
SET salary = 52000
WHERE emp_id = 101;
Explanation:
Updates the salary of an employee using the view. The base table Employees will be updated
as well.
4. Dropping a View
Query:
DROP VIEW HighSalaryEmployees;
Explanation:
Removes the view from the database.
Conclusion:
Views in SQL provide a virtual table to simplify complex queries, improve security, and
allow limited updates. This experiment demonstrated how to create, use, update through, and
drop a view.
Assignment N0-8
Aim:
To perform SQL queries that demonstrates the use of:
Transactions
COMMIT
ROLLBACK
CHECKPOINT
Software/Tools Required:
MySQL / PostgreSQL / SQL Server
SQL client (MySQL Workbench, pgAdmin, SSMS, etc.)
Database Schema:
CREATE TABLE BankAccounts (
account_id INT PRIMARY KEY,
account_holder VARCHAR(50),
balance DECIMAL(10, 2)
);
Insert Sample Data:
INSERT INTO BankAccounts (account_id, account_holder, balance) VALUES
(1, 'Alice', 1000.00),
(2, 'Bob', 1500.00);
1. Begin Transaction
Start a transaction using the command below:
START TRANSACTION;
-- or
BEGIN;
2. Perform a Transaction (Money Transfer)
Example: Transfer ₹200 from Alice to Bob
START TRANSACTION;
UPDATE BankAccounts SET balance = balance - 200 WHERE account_holder = 'Alice';
UPDATE BankAccounts SET balance = balance + 200 WHERE account_holder = 'Bob';
-- View balances before committing
SELECT * FROM BankAccounts;
3. Use COMMIT
COMMIT;
Explanation:
This saves the transaction permanently to the database.
4. Use ROLLBACK
Try a transaction, but then cancel it using ROLLBACK.
START TRANSACTION;
UPDATE BankAccounts SET balance = balance - 500 WHERE account_holder = 'Alice';
UPDATE BankAccounts SET balance = balance + 500 WHERE account_holder = 'Bob';
-- Something goes wrong, so cancel the transaction
ROLLBACK;
-- View to confirm rollback
SELECT * FROM BankAccounts;
Explanation:
This undoes all changes made in the current transaction block.
5. CHECKPOINT (SQL Server / PostgreSQL)
Note: MySQL does not support the CHECKPOINT command explicitly.
In SQL Server or PostgreSQL, you can use:
CHECKPOINT;
Explanation:
Forces the database engine to write all dirty pages (modified data) to disk. It is usually used
for recovery and performance tuning, not required in basic MySQL setups.
Conclusion:
This experiment demonstrates how SQL manages database changes using transactions,
allowing you to either save changes (COMMIT) or undo them (ROLLBACK). In
advanced systems, CHECKPOINT ensures data consistency during system crashes.
Assignment No-9
Aim:
1. Understand the concept and implementation of Triggers in SQL.
2. Learn to create and use Stored Procedures to automate tasks.
Part 1: Triggers in SQL
What is a Trigger? A trigger is a special type of stored procedure that automatically runs
when an event occurs in the database. Triggers are typically used to maintain data integrity.
Types of Triggers:
1. BEFORE Trigger: Executes before an insert, update, or delete operation.
2. AFTER Trigger: Executes after an insert, update, or delete operation.
3. INSTEAD OF Trigger: Executes instead of an insert, update, or delete operation.
Exercise 1.1: Create an Insert Trigger
1. Objective: Create a trigger that logs changes in a table whenever a new record is
inserted.
Table Setup:
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY,
Name VARCHAR(50),
Position VARCHAR(50)
);
CREATE TABLE EmployeeLog (
LogID INT PRIMARY KEY AUTO_INCREMENT,
EmployeeID INT,
Action VARCHAR(50),
ActionDate DATETIME
);
Create the Trigger:
DELIMITER //
CREATE TRIGGER EmployeeInsertTrigger
AFTER INSERT ON Employee
FOR EACH ROW
BEGIN
INSERT INTO EmployeeLog (EmployeeID, Action, ActionDate)
VALUES (NEW.EmployeeID, 'INSERT', NOW());
END;
//
DELIMITER ;
Test the Trigger:
INSERT INTO Employee (EmployeeID, Name, Position)
VALUES (1, 'John Doe', 'Developer');
SELECT * FROM EmployeeLog;
Expected Output: After inserting a new record into the Employee table, a log entry
should appear in the EmployeeLog table with the action recorded as "INSERT".
Part 2: Stored Procedures in SQL
What is a Stored Procedure? A stored procedure is a set of SQL statements that you can
execute together as a single unit. It helps in improving performance and reusability.
Exercise 2.1: Create a Simple Stored Procedure
Objective: Create a stored procedure to insert a new employee record.
Table Setup:
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(50),
Position VARCHAR(50)
);
Create the Stored Procedure:
DELIMITER //
CREATE PROCEDURE AddEmployee(IN emp_name VARCHAR(50), IN
emp_position VARCHAR(50))
BEGIN
INSERT INTO Employee (Name, Position)
VALUES (emp_name, emp_position);
END;
//
DELIMITER ;
Call the Stored Procedure:
CALL AddEmployee('Jane Smith', 'Manager');
SELECT * FROM Employee;
Expected Output: The employee "Jane Smith" with position "Manager" will be inserted
into the Employee table.
Part 3: Using Triggers and Stored Procedures Together
Exercise 3.1: Use a Trigger and Stored Procedure Together
Objective: Create a stored procedure that updates an employee’s position, and use a
trigger to log the action.
Table Setup:
CREATE TABLE Employee (
EmployeeID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(50),
Position VARCHAR(50)
);
CREATE TABLE EmployeeLog (
LogID INT PRIMARY KEY AUTO_INCREMENT,
EmployeeID INT,
Action VARCHAR(50),
ActionDate DATETIME
);
Create the Trigger:
DELIMITER //
CREATE TRIGGER EmployeeUpdateTrigger
AFTER UPDATE ON Employee
FOR EACH ROW
BEGIN
INSERT INTO EmployeeLog (EmployeeID, Action, ActionDate)
VALUES (NEW.EmployeeID, 'UPDATE', NOW());
END;
//
DELIMITER ;
Create the Stored Procedure:
DELIMITER //
CREATE PROCEDURE UpdateEmployeePosition(IN emp_id INT, IN new_position
VARCHAR(50))
BEGIN
UPDATE Employee
SET Position = new_position
WHERE EmployeeID = emp_id;
END;
//
DELIMITER ;
Call the Stored Procedure and Test:
CALL UpdateEmployeePosition(1, 'Senior Developer');
SELECT * FROM Employee;
SELECT * FROM EmployeeLog;
Expected Output: The Employee table should show the updated position, and the
EmployeeLog table should log the update action.
Conclusion:
This lab manual demonstrates the use of Triggers to automate actions in response to database
changes, and Stored Procedures to encapsulate reusable SQL logic. Both techniques help in
improving data integrity, performance, and maintainability of database applications.
Assignment No-10
Aim:
1. Understand the core concepts of NoSQL databases.
2. Learn how to interact with NoSQL databases like MongoDB.
3. Explore different types of NoSQL databases and their use cases.
Part 1: Introduction to NoSQL
What is NoSQL?
NoSQL stands for "Not Only SQL." These databases are designed for scalability, flexibility,
and performance in handling large volumes of unstructured or semi-structured data. Unlike
traditional relational databases (RDBMS), NoSQL databases do not require a fixed schema or
table structures.
Types of NoSQL Databases:
1. Document Store: Stores data as documents (e.g., JSON, BSON). Example:
MongoDB, CouchDB.
2. Key-Value Store: Stores data as key-value pairs. Example: Redis, Riak.
3. Column Store: Organizes data by columns instead of rows. Example: Cassandra,
HBase.
4. Graph Database: Designed to store and query graph data (nodes, edges). Example:
Neo4j, ArangoDB.
Part 2: Setup and Basics of MongoDB (Document Store)
Prerequisites:
Install MongoDB (or use a cloud-based MongoDB service like MongoDB Atlas).
Exercise 2.1: Install MongoDB and Start Mongo Shell
1. Download and Install MongoDB from the official website:
https://www.mongodb.com/try/download/community
2. Once installed, open the command line and type the following command to start
MongoDB:
3. mongod
4. In a new terminal window, connect to the MongoDB shell:
5. mongo
Part 3: Working with MongoDB (Document Store)
Exercise 3.1: Create a Database and Collection
Create a New Database:
use mydatabase;
Create a Collection and Insert Data: Collections in MongoDB are similar to tables in
RDBMS.
db.users.insertOne({
name: "John Doe",
age: 30,
email: "[email protected]"
});
View the Data:
db.users.find();
Expected Output: You should see the document inserted into the users collection.
Exercise 3.2: Query Data
Querying Specific Fields:
db.users.find({ name: "John Doe" });
Query with Conditions:
db.users.find({ age: { $gte: 18 } });
Operators:
o $gte: Greater than or equal to.
o $lte: Less than or equal to.
o $eq: Equal to.
Exercise 3.3: Update Documents
Update One Document:
db.users.updateOne({ name: "John Doe" }, { $set: { age: 31 } });
Update Multiple Documents:
db.users.updateMany({ age: { $gte: 30 } }, { $set: { status: "active" } });
Exercise 3.4: Delete Documents
Delete One Document:
db.users.deleteOne({ name: "John Doe" });
Delete Many Documents:
db.users.deleteMany({ age: { $lt: 25 } });
Part 4: Advanced MongoDB Operations
Exercise 4.1: Indexing in MongoDB
Create an Index: Indexes in MongoDB are used to improve query performance.
db.users.createIndex({ email: 1 });
Check Existing Indexes:
db.users.getIndexes();
Part 5: Exploring Other Types of NoSQL Databases
Key-Value Store: Redis
Install Redis from the official website: https://redis.io/download
Start Redis Server:
redis-server
Connect to Redis CLI:
redis-cli
Basic Operations:
o Set a key-value pair:
o SET name "Alice"
o Get a value by key:
o GET name
Column Store: Cassandra
Install Cassandra from the official website: https://cassandra.apache.org/
Start Cassandra and connect using the CQL Shell:
cqlsh
Create a Keyspace and Table:
CREATE KEYSPACE mykeyspace WITH replication = {'class': 'SimpleStrategy',
'replication_factor': 1};
USE mykeyspace;
CREATE TABLE users (
user_id UUID PRIMARY KEY,
name TEXT,
email TEXT
);
Insert and Query Data:
INSERT INTO users (user_id, name, email) VALUES (uuid(), 'John Doe',
'[email protected]');
SELECT * FROM users;
Part 6: Use Cases of NoSQL Databases
1. Document Stores (e.g., MongoDB):
o Suitable for content management systems, blogs, product catalogs.
o Handles semi-structured data (e.g., JSON or BSON format).
2. Key-Value Stores (e.g., Redis):
o Best for session management, caching, and real-time applications.
3. Column Stores (e.g., Cassandra):
o Ideal for handling large amounts of data across distributed systems.
o Common in time-series data, event logging, and analytics.
4. Graph Databases (e.g., Neo4j):
o Useful for social networks, recommendation systems, fraud detection, and
network analysis.
Conclusion:
This lab manual demonstrates the core concepts of NoSQL databases and provides hands-on
exercises with MongoDB, Redis, and Cassandra. NoSQL databases are powerful tools for
managing unstructured and semi-structured data, enabling scalability and flexibility in
modern applications.