Dbms Draft3

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 56

DBMS CHEATSHEET ANSWERS

1) Consider the relation employee (emp_id,e_name,salary ,Date of Joining,Dapt_no,Designation) perform basic operations.

1. Create table employee.


2. Insert 10 records in table.
3. Create a view emp_vl of table employee which has emp_id, name and dept-attributes.
4. Create view of table.
5. Update dept of any employee in view. Check whether it gets updated or not.
6. Create emp_id as primary key and show indices on table employee.
7. Show indices on table.
8. Create user defined index on any column.

Answer:

1. Create the "employee" table:

CREATE TABLE employee (

emp_id INT PRIMARY KEY,

e_name VARCHAR(50),

salary DECIMAL(10, 2),

Date_of_Joining DATE,

Dept_no INT,

Designation VARCHAR(50)

);

2. Insert 10 records into the "employee" table:

INSERT INTO employee (emp_id, e_name, salary, Date_of_Joining, Dept_no, Designation)

VALUES

(1, 'John Doe', 50000.00, '2023-01-15', 101, 'Manager'),

(2, 'Jane Smith', 45000.00, '2023-02-20', 102, 'Engineer'),

-- Add more records here

(10, 'Tom Brown', 60000.00, '2023-03-10', 101, 'Supervisor');

SELECT * FROM employee;

3. Create a view "emp_vl" of the "employee" table with only "emp_id," "e_name," and "Dept_no" attributes:

CREATE VIEW emp_vl AS

SELECT emp_id, e_name, Dept_no

FROM employee;

SELECT * FROM emp_v1;

4. Create view of table:

CREATE VIEW emp_v2 AS

SELECT * FROM employee;

SELECT * FROM emp_v2;


5. Update the "Dept_no" of any employee in the "emp_vl" view:

UPDATE emp_vl

SET Dept_no = 103

WHERE emp_id = 2;

SELECT * FROM emp_v1;

8. Create a user-defined index on any column. Let's create an index on the "e_name" column:

CREATE INDEX idx_e_name ON employee (e_name);

7. Show the indices on the "employee" table:

SHOW INDEXES FROM employee;


2) Consider the relation employee (emp_id,e_name,salary ,Date of Joining,Dept_no,Designation) perform basic operations.

1. Display employees whose name contains letter ‘e’.


2. Display different types of designation
3. Display name and salary of employee whose location is Mumbai
4. Display name and department of employee working in Manager or Marketing department
5. Display the department name whose employees are more than one
6. Rename employee table as emp1
7. Add a new column city in the employee table.

Answer:
1. Display employees whose name contains the letter 'e':
SELECT * FROM employee WHERE e_name LIKE '%e%';
2. Display different types of designations:
SELECT DISTINCT Designation FROM employee;
3. Display the name and salary of employees whose location is Mumbai:
SELECT e_name, salary FROM employee WHERE Dept_no = 'Mumbai';
4. Display the name and department of employees working in the Manager or Marketing department:
SELECT e_name, Dept_no FROM employee WHERE Designation = ‘manager’ OR Designation=’marketing’;
5. Display the department name whose employees are more than one:
SELECT Dept_no
FROM employee
GROUP BY Dept_no
HAVING COUNT(*) > 1;
6. Rename the employee table as emp1:
ALTER TABLE employee RENAME TO emp1;
7. Add a new column "city" to the employee table:
ALTER TABLE employee ADD city VARCHAR(255);
3)Consider the relation employee(emp_id,e_name,salary ,Date of Joining,Dept_no,Designation) perform basic operations.

1. Find department in which maximum employees work.


2. Display name, designation and department no of employees whose name starts with either ‘A’ or ‘P’.
3. Display max. salary from department 2 and min. salary from department 4.
4. Display employee data where salary is less than average salary from department 3.
5. Display employees who were hired earliest or latest.
6. Display name and department no of employees who are manager, market analysts. Use predicates
7. List employees hired in August.
8. List employees who are hired after 31/12/2006.
9. Find average annual salary per department.

Answer:
CREATE TABLE employee (

emp_id INT PRIMARY KEY,

e_name VARCHAR(50),

salary DECIMAL(10, 2),

Date_of_Joining DATE,

Dept_no INT,

Designation VARCHAR(50)

);

1. Find the department in which the maximum number of employees work:

SELECT Dept_no, COUNT(*) AS employee_count

FROM employee

GROUP BY Dept_no

ORDERS BY employee_count DESC

LIMIT 1;

2. Display the name, designation, and department number of employees whose names start with either 'A' or 'P':

SELECT e_name, Designation, Dept_no

FROM employee

WHERE e_name LIKE 'A%' OR e_name LIKE 'P%';

3. Display the maximum salary from department 2 and the minimum salary from department 4:

SELECT MAX(salary) AS max_salary_dept2, MIN(salary) AS min_salary_dept4

FROM employee

WHERE Dept_no = 2 OR Dept_no = 4;

4. Display employee data where the salary is less than the average salary from department 3:

SELECT *

FROM employee

WHERE salary < (SELECT AVG(salary) FROM employee WHERE Dept_no = 3);

5. Display employees who were hired earliest or latest:

To display employees hired earliest:

SELECT *

FROM employee
ORDERS BY Date_of_Joining

LIMIT 1;

To display employees hired latest:

SELECT *

FROM employee

ORDERS BY Date_of_Joining DESC

LIMIT 1;

6. Display the name and department number of employees who are managers or market analysts using predicates:

SELECT e_name, Dept_no

FROM employee

WHERE Designation IN ('Manager', 'Market Analyst');

7. List employees hired in August:

SELECT *

FROM employee

WHERE MONTH(Date_of_Joining) = 8;

8. List employees who were hired after December 31, 2006:

SELECT *

FROM employee

WHERE Date_of_Joining > '2006-12-31';

9. Find the average annual salary per department:

SELECT Dept_no, AVG(salary) AS avg_salary

FROM employee

GROUP BY Dept_no;
4)Consider two tables Customer(c_id, c_name , email , city , pincode) and Orders(Order_id , date , amount , cust_id).

1. Create both the tables with primary key and foreign key constraints.
2. insert 10 records each.
3. Find all Orderss placed by customers with cust_id2
4. Find list of customers who placed their Orders and details of Orders
5. List of customers who haven’t placed Orders
6. List all Orderss and append to customer table
7. Display all records
8. Display customer that are from same city

Answer:
1. Create the tables with primary key and foreign key constraints:
-- Create the Customer table:
CREATE TABLE Customer (
c_id INT PRIMARY KEY,
c_name VARCHAR(50),
email VARCHAR(50),
city VARCHAR(50),
pincode INT
);

-- Create the Orders table with a foreign key constraint on cust_id


CREATE TABLE Orders (
Order_id INT PRIMARY KEY,
date DATE,
amount DECIMAL(10, 2),
cust_id INT,
FOREIGN KEY (cust_id) REFERENCES Customer(c_id)
);
2. Insert 10 records into each table (Sample data):
-- Insert records into the Customer table
INSERT INTO Customer (c_id, c_name, email, city, pincode)
VALUES
(1, 'Alice', '[email protected]', 'New York', 10001),
(2, 'Bob', '[email protected]', 'Los Angeles', 90001),
(3, 'Charlie', '[email protected]', 'Chicago', 60601),
-- Add more records here...

-- Insert records into the Orders table


INSERT INTO Orders (Order_id, date, amount, cust_id)
VALUES
(101, '2023-01-10', 100.00, 1),
(102, '2023-02-15', 150.00, 1),
(103, '2023-02-20', 75.00, 2),
-- Add more records here...
3. Find all Orderss placed by customers with cust_id 2:
SELECT * FROM Orders WHERE cust_id = 2;
4. Find a list of customers who placed Orderss and the details of those Orderss:
SELECT c.c_name, o.*
FROM Customer c
INNER JOIN Orders o ON c.c_id = o.cust_id;
5. List of customers who haven't placed an Orders:
SELECT c.c_name
FROM Customer c
LEFT JOIN Orders o ON c.c_id = o.cust_id
WHERE o.cust_id IS NULL;
6. List all Orderss and append them to the customer table (This is not a standard practice but can be done for specific
use cases):
SELECT c.*, o.*
FROM Customer c
LEFT JOIN Orders o ON c.c_id = o.cust_id;
7. Display all records from both tables:
-- Retrieve all records from Customer and matching records from Orders
SELECT c.*, o.Order_id, o.date, o.amount
FROM Customer c
LEFT JOIN Orders o ON c.c_id = o.cust_id
UNION
-- Retrieve all records from Orders and non-matching records from Customer
SELECT c.*, o.Order_id, o.date, o.amount
FROM Orders o
LEFT JOIN Customer c ON o.cust_id = c.c_id
WHERE c.c_id IS NULL;

8. Display customers that are from the same city:


SELECT c1.c_name, c2.c_name
FROM Customer c1
JOIN Customer c2 ON c1.city = c2.city AND c1.c_id <> c2.c_id;
5) Consider tables Borrower (RollNo, Name, DateofIssue, NameofBook, Status) and
Fine (Roll_no,Date,Amt). Status is either Issued or Returned.
1. Create both the tables with primary key.
2. Insert 10 records each.
3. Find count of books with Issued status.
4. Display all records.
5. Display RollNo whose date of issue is same.

Answer:
1. Create both tables with primary keys:
-- Create the Borrower table
CREATE TABLE Borrower (
RollNo INT PRIMARY KEY,
Name VARCHAR(50),
DateofIssue DATE,
NameofBook VARCHAR(50),
Status VARCHAR(10)
);

-- Create the Fine table


CREATE TABLE Fine (
Roll_no INT PRIMARY KEY,
Date DATE,
Amt DECIMAL(10, 2)
);
2. Insert 10 records each:
For the Borrower table:
INSERT INTO Borrower (RollNo, Name, DateofIssue, NameofBook, Status)
VALUES
(1, 'John Doe', '2023-01-10', 'Book1', 'Issued'),
(2, 'Jane Smith', '2023-01-15', 'Book2', 'Returned'),
(3, 'Alice Johnson', '2023-01-20', 'Book3', 'Issued'),
(4, 'Bob Wilson', '2023-02-01', 'Book4', 'Returned'),
(5, 'Charlie Brown', '2023-02-05', 'Book1', 'Issued'),
(6, 'David Smith', '2023-02-10', 'Book2', 'Returned'),
(7, 'Eva Martinez', '2023-02-15', 'Book3', 'Issued'),
(8, 'Frank Lee', '2023-02-20', 'Book4', 'Returned'),
(9, 'Grace Anderson', '2023-02-25', 'Book5', 'Issued')
(10, 'Tom Brown', '2023-01-25', 'Book5', 'Issued');

For the Fine table:


INSERT INTO Fine (Roll_no, Date, Amt)
VALUES
(1, '2023-01-20', 5.00),
(3, '2023-01-18', 10.00),
-- Add more records here
(10, '2023-01-30', 8.50);
3. Find the count of books with the "Issued" status:
SELECT COUNT(*) AS IssuedBookCount
FROM Borrower
WHERE Status = 'Issued';
4. Display all records from both tables:
-- Retrieve all records from Borrower and matching records from Fine
SELECT Borrower.*, Fine.Date, Fine.Amt
FROM Borrower
LEFT JOIN Fine ON Borrower.RollNo = Fine.Roll_no
UNION
-- Retrieve all records from Fine and non-matching records from Borrower
SELECT Borrower.*, Fine.Date, Fine.Amt
FROM Fine
LEFT JOIN Borrower ON Fine.Roll_no = Borrower.RollNo
WHERE Borrower.RollNo IS NULL;
5. Display RollNo whose date of issue is the same:
SELECT RollNo, DateofIssue
FROM Borrower
GROUP BY RollNo, DateofIssue
HAVING COUNT(*) > 1;
6) Consider student (roll_no, name, marks, class) table. Column roll_no is primary key. Perform any 3 DLL and any 3 DML
operations on the table.

Answer:
Data Definition Language (DDL) Operations:
1. Create Table:
CREATE TABLE student (
roll_no INT PRIMARY KEY,
name VARCHAR(50),
marks INT,
class VARCHAR(10)
);
2. Alter Table:
ALTER TABLE student
ADD dob DATE;
3. Drop Table:
DROP TABLE student;

Data Manipulation Language (DML) Operations:


1. Insert Data:
INSERT INTO student (roll_no, name, marks, class)
VALUES (1, 'John Doe', 95, '10A');
2. Update Data:
UPDATE student
SET marks = 98
WHERE roll_no = 1;
3. Delete Data:
DELETE FROM student
WHERE roll_no = 1;
7) Write a statement to create a table job_history including columns employee_id, start_date, end_date, job_id and
department_id and make sure that, the employee_id column does not contain any duplicate value at the time of insertion and
the foreign key column job_id contain only those values which are exists in the jobs table. Consider table Job
(job_id,job_title.min_sal,max_sal)

Answer:
CREATE TABLE jobs (
job_id VARCHAR(10) PRIMARY KEY,
job_title VARCHAR(50),
min_sal DECIMAL(10, 2),
max_sal DECIMAL(10, 2)
);
1.Insert some sample data into the "jobs" table
INSERT INTO jobs (job_id, job_title, min_sal, max_sal)
VALUES
('J001', 'Manager', 50000.00, 80000.00),
('J002', 'Engineer', 40000.00, 70000.00),
('J003', 'Analyst', 35000.00, 60000.00),
('J004', 'Designer', 38000.00, 65000.00),
-- Add more job records here
('J005', 'Supervisor', 45000.00, 75000.00);

2 Create the table Required in Question:


CREATE TABLE job_history (
employee_id INT PRIMARY KEY,
start_date DATE,
end_date DATE,
job_id VARCHAR(10),
department_id INT,
FOREIGN KEY (job_id) REFERENCES jobs (job_id)
);

-- This unique constraint ensures that employee_id does not contain duplicate values
CREATE UNIQUE INDEX idx_employee_id ON job_history (employee_id);
8) For the given relation schema: employee (employee-name, street, city)
works (employee-name, company-name, salary)
company (company-name, city)
manages (employee-name, manager-name)
Give an expression in for each of the following queries:
a) Find the names, street address, and cities of residence for all employees who work for same company and earn
more than $10,000.
b) Find the names of all employees in the database who live in the same cities as the companies for which they work.
c) Find the names of all employees who earn more than the average salary of all employees of their company. Assume
that all people work for at most one company.

Answer:

a) To find the names, street address, and cities of residence for all employees who work for the same company and
earn more than $10,000, you can use a query like this:
SELECT e.employee-name, e.street, e.city
FROM employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.salary > 10000
AND w.company-name IN (
SELECT company-name
FROM works
GROUP BY company-name
HAVING COUNT(DISTINCT employee-name) > 1
);
b) To find the names of all employees in the database who live in the same cities as the companies for which they
work, you can use the following query:
SELECT DISTINCT e.employee-name
FROM employee e
JOIN works w ON e.employee-name = w.employee-name
JOIN company c ON w.company-name = c.company-name
WHERE e.city = c.city;
c) To find the names of all employees who earn more than the average salary of all employees of their company, you
can use this query:
SELECT e.employee-name
FROM employee e
JOIN works w ON e.employee-name = w.employee-name
WHERE w.salary > (
SELECT AVG(salary)
FROM works
WHERE company-name = w.company-name
);
9) For the given relation schema: employee (employee-name, street, city)
works (employee-name, company-name, salary)
company (company-name, city)
manages (employee-name, manager-name)
Give an expression in for each of the following queries:
a) Find the name of the company that has the smallest payroll.
b) Find the names of all employees in the database who live in the same cities and on the same streets as do their
managers.

Answers:
a) To find the name of the company with the smallest payroll, you can use the following query:
SELECT company_name
FROM works
GROUP BY company_name
HAVING SUM(salary) = (SELECT MIN(total_salary)
FROM (SELECT company_name, SUM(salary) AS total_salary
FROM works
GROUP BY company_name) AS payroll);
b) To find the names of employees who live in the same cities and on the same streets as their managers, you can use
the following query:
SELECT e.employee_name
FROM employee e
INNER JOIN manages m ON e.employee_name = m.employee_name
WHERE e.street = (SELECT street FROM employee WHERE employee_name = m.manager_name)
AND e.city = (SELECT city FROM employee WHERE employee_name = m.manager_name);
10) Implement CRUD operations. SAVE method. Use following Collection. Perform Map Reduce to count quantity of each
item.

Item: Item ID, Item quantity, price, brand, discount


1. Display the count of item brand wise.
2. Display item with minimum price.
3. Display maximum discount given for item.

Answer
Step 1: Create a MongoDB Database and Collection

use my_store
db.createCollection("items")
Step 2: Insert Sample Data

db.items.insertMany([
{ "Item ID": 1, "Item quantity": 10, "price": 50, "brand": "Brand A", "discount": 5 },
{ "Item ID": 2, "Item quantity": 5, "price": 30, "brand": "Brand B", "discount": 10 },
{ "Item ID": 3, "Item quantity": 8, "price": 40, "brand": "Brand A", "discount": 3 },
{ "Item ID": 4, "Item quantity": 12, "price": 60, "brand": "Brand C", "discount": 8 },
{ "Item ID": 5, "Item quantity": 6, "price": 45, "brand": "Brand B", "discount": 5 }
])
Step 3: Perform the Requested Operations:
a) Display the count of items brand-wise:

var mapFunction = function () {


emit(this.brand, this.itemQuantity);
};

var reduceFunction = function (key, values) {


return Array.sum(values);
};

db.items.mapReduce(mapFunction, reduceFunction, {
out: "brandItemCount",
});
// To retrieve the result
db.brandItemCount.find();

//Aggregate Equivalent
db.items.aggregate([
{
$group: {
_id: "$brand",
count: { $sum: 1 }
}
}
])

b) Display the item with the minimum price:

db.items.find().sort({ price: 1 }).limit(1)


c) Display the item with the maximum discount:

db.items.find().sort({ discount: -1 }).limit(1)


Step 4: Retrieve and View Results
11) Implement CRUD operations. SAVE method. Use following Collection.
Item: Item ID, Item quantity, price, brand, discount
1. Display the count of item brand wise.
2. Display item with minimum price.
3. Display maximum discount given for item.

Answer:
Step 1: Create a MongoDB Database and Collection

use my_store
db.createCollection("items")
Step 2: Insert Sample Data

db.items.insertMany([
{ "Item ID": 1, "Item quantity": 10, "price": 50, "brand": "Brand A", "discount": 5 },
{ "Item ID": 2, "Item quantity": 5, "price": 30, "brand": "Brand B", "discount": 10 },
{ "Item ID": 3, "Item quantity": 8, "price": 40, "brand": "Brand A", "discount": 3 },
{ "Item ID": 4, "Item quantity": 12, "price": 60, "brand": "Brand C", "discount": 8 },
{ "Item ID": 5, "Item quantity": 6, "price": 45, "brand": "Brand B", "discount": 5 }
])
Step 3: Perform the Requested Operations
a) Display the count of items brand-wise:

db.items.aggregate([
{
$group: {
_id: "$brand",
count: { $sum: 1 }
}
}
])

b) Display the item with the minimum price:

db.items.find().sort({ price: 1 }).limit(1)


c) Display the item with the maximum discount:
db.items.find().sort({ discount: -1 }).limit(1)
Step 4: Retrieve and View Results
12) Implement CRUD operations. SAVE method. Use following Collection.
Item: Item ID, Item quantity, price, brand, discount
1. Display the count of item brand wise.
2. Display item with minimum price.
3. Display maximum discount given for item.

Question 12
1. *Install and Set Up MongoDB*: If you haven't already, install and set up MongoDB on your system.
2. *Use MongoDB Shell or a MongoDB Driver for Your Preferred Programming Language*: You can use
MongoDB Shell directly or a MongoDB driver for your preferred programming language (e.g., PyMongo
for Python).
Here's a step-by-step guide using MongoDB Shell to create and interact with the collection and perform the
requested operations:
*Step 1: Create a Database and a Collection*
Start the MongoDB shell by running mongo in your terminal. Then, create a new database and a collection
for your items:

use mystore
db.createCollection("items")

*Step 2: Insert Sample Data*


Insert some sample data into the "items" collection:

db.items.insertMany([
{
"Item ID": 1,
"Item quantity": 10,
"price": 50,
"brand": "Brand A",
"discount": 5
},
{
"Item ID": 2,
"Item quantity": 5,
"price": 30,
"brand": "Brand B",
"discount": 10
},
{
"Item ID": 3,
"Item quantity": 8,
"price": 40,
"brand": "Brand A",
"discount": 3
},
{
"Item ID": 4,
"Item quantity": 12,
"price": 60,
"brand": "Brand C",
"discount": 8
},
{
"Item ID": 5,
"Item quantity": 6,
"price": 45,
"brand": "Brand B",
"discount": 5
}
])

*Step 3: Perform the Requested Operations*


a) Display the count of items brand-wise:

db.items.aggregate([
{ $group: { _id: "$brand", count: { $sum: 1 } } }
])

b) Display the item with the minimum price:

db.items.find().sort({ price: 1 }).limit(1)


c) Display the item with the maximum discount:

db.items.find().sort({ discount: -1 }).limit(1)


13) Implement Map reduces operation for counting the marks of students.

Use: student (roll_no, name marks, class)

Expected output: student name or roll no and total marks.

Answer:
*Step 1: Create a MongoDB Database and Collection*

use school
db.createCollection("students")

*Step 2: Insert Sample Data*


Insert some sample data into the "students" collection. Here's an example with a few student records:

db.students.insertMany([
{ roll_no: 1, name: "Alice", marks: 95, class: "10A" },
{ roll_no: 2, name: "Bob", marks: 85, class: "10A" },
{ roll_no: 3, name: "Charlie", marks: 92, class: "10B" },
{ roll_no: 4, name: "David", marks: 78, class: "10B" },
{ roll_no: 5, name: "Eve", marks: 88, class: "10A" }
])

*Step 3: Implement Map-Reduce*


Now, you can create a Map-Reduce function to count the total marks of students. In this example, we'll
group the students by their roll numbers and calculate the total marks for each student.

var mapFunction = function () {


emit(this.roll_no, this.marks);
};

var reduceFunction = function (key, values) {


return Array.sum(values);
};

db.students.mapReduce(
mapFunction,
reduceFunction,
{ out: "total_marks" }
)
This map function emits the roll number as the key and the marks as the value. The reduce function
calculates the total marks for each student.
//Aggregate Equivalent
db.students.aggregate([
{
$group: {
_id: "$roll_no",
total_marks: { $sum: "$marks" }
}
}
]);

*Step 4: Retrieve the Results*

You can retrieve the results of the Map-Reduce operation from the "total_marks" collection:

db.total_marks.find()

The output will show the student's roll number and their total marks:

json
{ "_id" : 1, "value" : 95 }
{ "_id" : 2, "value" : 85 }
{ "_id" : 3, "value" : 92 }
{ "_id" : 4, "value" : 78 }
{ "_id" : 5, "value" : 88 }
14) Implement Map reduces operation for displaying persons with same profession.

Use: person (person_id, name, addr, profession)

Answer:
*Step 1: Create a MongoDB Database and Collection*
Start by creating a MongoDB database and a collection for your "person" records if you haven't already.

use mydb
db.createCollection("persons")

*Step 2: Insert Sample Data*

Insert some sample data into the "persons" collection. Here's an example with a few person records:

db.persons.insertMany([
{ person_id: 1, name: "Alice", addr: "123 Main St", profession: "Doctor" },
{ person_id: 2, name: "Bob", addr: "456 Elm St", profession: "Engineer" },
{ person_id: 3, name: "Charlie", addr: "789 Oak St", profession: "Doctor" },
{ person_id: 4, name: "David", addr: "101 Pine St", profession: "Lawyer" },
{ person_id: 5, name: "Eve", addr: "202 Birch St", profession: "Engineer" }
])

*Step 3: Implement Map-Reduce*


Now, you can create a Map-Reduce function to group persons by their professions and display individuals
with the same profession.

var mapFunction = function () {


emit(this.profession, { persons: [{ name: this.name, person_id: this.person_id }] });
};

var reduceFunction = function (key, values) {


var result = { persons: [] };
values.forEach(function (value) {
result.persons = result.persons.concat(value.persons);
});
return result;
};

var finalizeFunction = function (key, reducedValue) {


return reducedValue;
};

db.persons.mapReduce(
mapFunction,
reduceFunction,
{ out: "same_profession", finalize: finalizeFunction }
)

//Aggregate version
db.persons.aggregate([
{
$group:{
_id:"$profession",
names:{$addToSet:"$name"}
}
}
])

This map function emits the profession as the key and an array containing person information as the value.
The reduce function combines the information of persons with the same profession into a single array.

*Step 4: Retrieve the Results*


You can retrieve the results of the Map-Reduce operation from the "same_profession" collection:
db.same_profession.find()

The output will show persons grouped by their profession:

json
{ "_id" : "Doctor", "value" : { "persons" : [ { "name" : "Alice", "person_id" : 1 }, { "name" : "Charlie",
"person_id" : 3 } ] } }
{ "_id" : "Engineer", "value" : { "persons" : [ { "name" : "Bob", "person_id" : 2 }, { "name" : "Eve",
"person_id" : 5 } ] } }
{ "_id" : "Lawyer", "value" : { "persons" : [ { "name" : "David", "person_id" : 4 } ] } }

This demonstrates a basic Map-Reduce operation in MongoDB to group persons by their professions and
display individuals with the same profession. You can further customize the map and reduce functions to suit
your specific requirments
15) Perform CRUD operation in mongo db –

Use : person( person_id, name, addr, profession )

1.Create Collection.

2.Inserting data in collection.

3.Reading data of collection.

4.Updating data of collection.

5.Deleting data from collection.

Question 15

To perform CRUD (Create, Read, Update, Delete) operations in MongoDB for the "person" collection, you can follow these steps:

*Step 1: Create a MongoDB Database and Collection*

Create a MongoDB database (if it doesn't already exist) and a collection for your "person" records.

use mydb

db.createCollection("person")

*Step 2: Insert Data into the Collection*

Insert data into the "person" collection. Here's an example with a few person records:

db.person.insertMany([

{ "person_id": 1, "name": "Alice", "addr": "123 Main St", "profession": "Engineer" },

{ "person_id": 2, "name": "Bob", "addr": "456 Elm St", "profession": "Doctor" },

{ "person_id": 3, "name": "Charlie", "addr": "789 Oak St", "profession": "Teacher" },

{ "person_id": 4, "name": "David", "addr": "101 Pine St", "profession": "Artist" },

{ "person_id": 5, "name": "Eve", "addr": "202 Maple St", "profession": "Lawyer" }

])

*Step 3: Read Data from the Collection*

You can read data from the "person" collection using queries. For example:

- To retrieve all documents in the collection:

db.person.find()
- To find a person by their name (e.g., "Alice"):

db.person.find({ "name": "Alice" })

*Step 4: Update Data in the Collection*

To update data in the collection, you can use the updateOne or updateMany methods. For example, to update the profession of a
person with "person_id" 2:

db.person.updateOne(

{ "person_id": 2 },

{ $set: { "profession": "Surgeon" } }

*Step 5: Delete Data from the Collection*

You can delete data from the collection using the deleteOne or deleteMany methods. For example, to delete a person by their
name (e.g., "David"):

db.person.deleteOne({ "name": "David" })


16) Perform CRUD operation and Aggregation in mongo db

employee(emp_id,e_name,salary ,Date of Joining,Dapt_no,Designation)

1. Display the count of employee department wise.

2. Display the average salary of employee in sales department.

3. Display minimum salary to employees joins in June 2016

4. Display maximum salary given to employee in production department.

5. Display record of first and last employee department wise.

Answer:

*Step 1: Create a MongoDB Database and Collection*


Start by creating a MongoDB database and a collection for your "employee" records if you haven't already.
For this example, we'll use a database named company and a collection named employees.

use company
db.createCollection("employees")

*Step 2: Insert Sample Data*


Insert some sample data into the "employees" collection. Here's an example with a few employee records:

db.employees.insertMany([
{ emp_id: 1, e_name: "Alice", salary: 60000, Date_of_Joining: ISODate("2016-06-01"), Dept_no: 101,
Designation: "Sales Executive" },
{ emp_id: 2, e_name: "Bob", salary: 75000, Date_of_Joining: ISODate("2017-05-15"), Dept_no: 101,
Designation: "Sales Manager" },
{ emp_id: 3, e_name: "Charlie", salary: 55000, Date_of_Joining: ISODate("2016-06-10"), Dept_no: 102,
Designation: "Production Operator" },
{ emp_id: 4, e_name: "David", salary: 80000, Date_of_Joining: ISODate("2018-04-20"), Dept_no: 103,
Designation: "HR Manager" },
{ emp_id: 5, e_name: "Eve", salary: 70000, Date_of_Joining: ISODate("2016-06-25"), Dept_no: 102,
Designation: "Production Supervisor" }
])

*Step 3: Perform CRUD Operations*


You can perform CRUD operations to manipulate and retrieve data in the "employees" collection. Here are
some examples:
- Insert a new employee:
db.employees.insert({
emp_id: 6,
e_name: "Frank",
salary: 65000,
Date_of_Joining: ISODate("2017-07-12"),
Dept_no: 101,
Designation: "Sales Executive"
})

- Update an employee's salary:

db.employees.updateOne({ e_name: "Alice" }, { $set: { salary: 62000 } })

- Delete an employee:

db.employees.deleteOne({ e_name: "David" })

*Step 4: Perform Aggregation Queries*


Now, let's perform the requested aggregation queries.
a) Display the count of employees department-wise:
db.employees.aggregate([
{
$group: {
_id: "$Dept_no",
count: { $sum: 1 }
}
}
])

b) Display the average salary of employees in the Sales department (Dept_no 101):
db.employees.aggregate([
{
$match: { Dept_no: 101 }
},
{
$group: {
_id: "$Dept_no",
average_salary: { $avg: "$salary" }
}
}
])

c) Display the minimum salary of employees who joined in June 2016:

db.employees.find({ Date_of_Joining: { $gte: ISODate("2016-06-01"), $lt: ISODate("2016-07-


01") } }).sort({ salary: 1 }).limit(1)

d) Display the maximum salary given to employees in the Production department (Dept_no 102):

db.employees.find({ Dept_no: 102 }).sort({ salary: -1 }).limit(1)

e) Display the first and last employee's records department-wise:

db.employees.aggregate([
{
$sort: { Dept_no: 1, Date_of_Joining: 1 }
},
{
$group: {
_id: "$Dept_no",
first_employee: { $first: "$$ROOT" },
last_employee: { $last: "$$ROOT" }
}
}
])
//$$ROOT : references all records within the current context, in this case in each $group
instance

These queries will provide you with the desired results based on the specified criteria. You can run these
queries in the MongoDB shell to obtain the output.
17) Consider student ( roll_no, name ,marks, class) table. Perform add update and delete operation on same table
through java program. Write menu driven program.

Question 17
//needs mongodb-driver-core-4.11.0.jar from maven repo
create a new file named “.classpath” in same folder as the program
add:
<classpath>
<classpathentry kind="lib" path="path_to_jar "/>
</classpath>
And save
Make sure you have already created a database called “store” with a collection “students”
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Scanner;

public class random {


public static void main(String[] args) {
try (MongoClient mongoClient = MongoClients.create("mongodb://localhost:27017")) {
MongoDatabase database = mongoClient.getDatabase("store");
MongoCollection<Document> collection = database.getCollection("students");
Scanner scanner = new Scanner(System.in);

while (true) {
System.out.println("Student Management System");
System.out.println("1. Add Student");
System.out.println("2. Update Student");
System.out.println("3. Delete Student");
System.out.println("4. Exit");
System.out.print("Select an option: ");
int option = scanner.nextInt();

switch (option) {
case 1:
addStudent(collection, scanner);
break;
case 2:
updateStudent(collection, scanner);
break;
case 3:
deleteStudent(collection, scanner);
break;
case 4:
System.out.println("Exiting the program.");
scanner.close();
return;
default:
System.out.println("Invalid option. Please choose a valid option.");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

private static void addStudent(MongoCollection<Document> collection, Scanner scanner) {


System.out.print("Enter Roll No: ");
int rollNo = scanner.nextInt();
System.out.print("Enter Name: ");
String name = scanner.next();
System.out.print("Enter Marks: ");
double marks = scanner.nextDouble();
System.out.print("Enter Class: ");
String studentClass = scanner.next();
Document document = new Document("roll_no", rollNo)
.append("name", name)
.append("marks", marks)
.append("class", studentClass);

collection.insertOne(document);
System.out.println("Student added successfully.");
}

private static void updateStudent(MongoCollection<Document> collection, Scanner scanner) {


System.out.print("Enter Roll No of the student to update: ");
int rollNo = scanner.nextInt();
System.out.print("Enter new Name: ");
String name = scanner.next();
System.out.print("Enter new Marks: ");
double marks = scanner.nextDouble();
System.out.print("Enter new Class: ");
String studentClass = scanner.next();

Document filter = new Document("roll_no", rollNo);


Document update = new Document("$set",
new Document("name", name).append("marks", marks).append("class", studentClass));

collection.updateOne(filter, update);
System.out.println("Student updated successfully.");
}

private static void deleteStudent(MongoCollection<Document> collection, Scanner scanner) {


System.out.print("Enter Roll No of the student to delete: ");
int rollNo = scanner.nextInt();

Document filter = new Document("roll_no", rollNo);


collection.deleteOne(filter);
System.out.println("Student deleted successfully.");
}
}
18) Implement Stored Procedure namely proc_Grade for the categorization of student. If marks scored by students in
examination is <=1500 and marks>=990 then student will be placed in distinction category if marks scored are
between 989 and900 category is first class, if marks 899 and 825 category is Higher Second Class. Write a PL/ block
for using procedure created with above requirement. Stud_Marks(name, total_marks) Result(Roll,Name, Class).

Question 18
In PL/, you can create a stored procedure named proc_Grade to categorize students based on their marks in
an examination. Here's a PL/ block that defines the procedure and uses it to categorize students from the
Stud_Marks table and insert the results into the Result table:

-- Create a procedure to categorize students


CREATE OR REPLACE PROCEDURE proc_Grade IS
BEGIN
FOR stud_rec IN (SELECT name, total_marks FROM Stud_Marks) LOOP
INSERT INTO Result (Roll, Name, Class)
VALUES (stud_rec.name, stud_rec.total_marks,
CASE
WHEN stud_rec.total_marks >= 990 AND stud_rec.total_marks <= 1500 THEN 'Distinction'
WHEN stud_rec.total_marks >= 900 AND stud_rec.total_marks <= 989 THEN 'First Class'
WHEN stud_rec.total_marks >= 825 AND stud_rec.total_marks <= 899 THEN 'Higher Second
Class'
ELSE 'Fail'
END);
END LOOP;
END;
/

-- Execute the procedure to categorize students


EXEC proc_Grade;

In this PL/ block, we first create the proc_Grade procedure. Inside the procedure, we use a cursor to iterate
over the records in the Stud_Marks table. For each student, we determine their category based on their total
marks and then insert the result into the Result table. The CASE statement is used to categorize the students
according to the provided criteria.
Finally, we execute the proc_Grade procedure to categorize the students and insert the results into the Result
table.
Please ensure that you have the necessary tables (Stud_Marks and Result) and that you have the appropriate
privileges to create and execute procedures in your Oracle database. Adjust the table and column names as
needed to match your actual database schema.
19) Write a database trigger on customer( cust_id, c_name, addr) table. The System should keep track of the records
that are being updated or deleted. The old value of updated or deleted records should be added in cust_Audit table.

*Question 19*

-- Create the cust_Audit table to store old values


CREATE TABLE cust_Audit (
cust_id NUMBER,
c_name VARCHAR2(50),
addr VARCHAR2(100),
action_type VARCHAR2(10),
action_date TIMESTAMP
);

-- Create a trigger to capture updates and deletes


CREATE OR REPLACE TRIGGER customer_audit_trigger
AFTER DELETE OR UPDATE ON customer
FOR EACH ROW
DECLARE
v_action_type VARCHAR2(10);
BEGIN
IF DELETING THEN
v_action_type := 'DELETE';
ELSE
v_action_type := 'UPDATE';
END IF;

INSERT INTO cust_Audit (cust_id, c_name, addr, action_type, action_date)


VALUES (:OLD.cust_id, :OLD.c_name, :OLD.addr, v_action_type, SYSTIMESTAMP);
END;
/

In this example:
1. We first create a table called "cust_Audit" to store the old values of updated or deleted records.
2. We create a trigger named "customer_audit_trigger" on the "customer" table. This trigger fires after a row
is deleted or updated.
3. In the trigger body, we check whether the trigger action is a DELETE or an UPDATE.
4. For deleted records, we set the action_type to 'DELETE.' For updated records, we set it to 'UPDATE.'
5. We then insert the old values of the record (from the :OLD pseudo-record) along with the action type and
the current timestamp into the "cust_Audit" table.
With this trigger in place, the "cust_Audit" table will keep a record of deleted and updated records from the
"customer" table, including the old values and the type of action (delete or update).
20) Implement a database trigger on client_master( c_id, c_name, acc_no) table. The System should keep
track of the records that are being updated or inserted. The old value of updated or deleted records should be
added in client_Audit table.

1. Create the client_Audit table to store the old values of the records. The structure of the client_Audit table
should match that of the client_master table, and it should include additional columns for tracking changes
such as timestamp and the type of operation.

CREATE TABLE client_Audit (


c_id NUMBER,
c_name VARCHAR2(255),
acc_no VARCHAR2(50),
operation_type VARCHAR2(10), -- 'INSERT', 'UPDATE', or 'DELETE'
timestamp TIMESTAMP
);

2. Create a database trigger on the client_master table that captures the old values of records and inserts
them into the client_Audit table. The trigger can fire on both update and delete operations.
Here's an example of a trigger that captures the old values and logs them:

CREATE OR REPLACE TRIGGER client_master_audit_trigger


AFTER INSERT OR UPDATE OR DELETE ON client_master
FOR EACH ROW
DECLARE
BEGIN
IF INSERTING THEN
-- Insert operation
INSERT INTO client_Audit (c_id, c_name, acc_no, operation_type, timestamp)
VALUES (:new.c_id, :new.c_name, :new.acc_no, 'INSERT', SYSTIMESTAMP);
ELSIF UPDATING THEN
-- Update operation
INSERT INTO client_Audit (c_id, c_name, acc_no, operation_type, timestamp)
VALUES (:old.c_id, :old.c_name, :old.acc_no, 'UPDATE', SYSTIMESTAMP);
ELSIF DELETING THEN
-- Delete operation
INSERT INTO client_Audit (c_id, c_name, acc_no, operation_type, timestamp)
VALUES (:old.c_id, :old.c_name, :old.acc_no, 'DELETE', SYSTIMESTAMP);
END IF;
END;
/

This trigger, named client_master_audit_trigger, fires after an insert, update, or delete operation on the
client_master table. It uses conditional blocks to determine the type of operation and inserts the old values
into the client_Audit table along with a timestamp.

3. With the trigger in place, whenever a record is inserted, updated, or deleted in the client_master table, the
old values of the records are logged in the client_Audit table, along with the type of operation and a
timestamp.
Please make sure to adjust the trigger and table structures as needed to match your specific database
requirements. Additionally, ensure that you have the necessary privileges to create and use triggers in your
Oracle database.
21) Implement a PL/ block of code using explicit Cursor, that will merge the data available in the newly created table
N_RollCall with the data available in the table O_RollCall. If the data in the first table already exist in the second
table then that data should be skipped.

Question 21
You can use PL/ with an explicit cursor to merge data from the N_RollCall table into the O_RollCall table
while skipping data that already exists in the O_RollCall table. Here's a sample PL/ block that accomplishes
this:

DECLARE
-- Declare cursor to fetch data from N_RollCall
CURSOR n_cursor IS
SELECT *
FROM N_RollCall;

-- Variables to hold data from the cursor


n_roll_no N_RollCall.roll_no%TYPE;
n_student_name N_RollCall.student_name%TYPE;
n_attendance_status N_RollCall.attendance_status%TYPE;

-- Variable to check if data exists in O_RollCall


data_exists BOOLEAN;
BEGIN
-- Loop through the cursor for N_RollCall data
FOR n_rec IN n_cursor LOOP
-- Check if data exists in O_RollCall
SELECT COUNT(*)
INTO data_exists
FROM O_RollCall
WHERE roll_no = n_rec.roll_no
AND student_name = n_rec.student_name;

-- If data doesn't exist in O_RollCall, insert it


IF data_exists = 0 THEN
INSERT INTO O_RollCall (roll_no, student_name, attendance_status)
VALUES (n_rec.roll_no, n_rec.student_name, n_rec.attendance_status);
END IF;
END LOOP;

-- Commit the changes


COMMIT;

-- Display a message
DBMS_OUTPUT.PUT_LINE('Data from N_RollCall merged into O_RollCall.');
END;
/
In this PL/ block:

1. We declare a cursor n_cursor to fetch data from the N_RollCall table.


2. Inside the loop, we check if the data from N_RollCall already exists in the O_RollCall table by
performing a SELECT COUNT(*) query.
3. If the data doesn't exist in the O_RollCall table (data_exists = 0), we insert the data into O_RollCall.
4. After processing all the records, we commit the changes to the database.
5. Finally, we display a message to indicate that the data from N_RollCall has been merged into O_RollCall.
Please adjust the table and column names as per your database schema.
Question 22
To accomplish this task using PL/, you can create a PL/ block that accepts the roll_no and name_of_book from the
user, calculates the number of days since the book was issued, and, if the conditions are met, stores the fine details in
the Fine table. Here's a sample PL/ block to achieve this:

-- Create the Borrower and Fine tables if they don't exist


CREATE TABLE Borrower (
Roll_no NUMBER,
Name VARCHAR2(100),
DateofIssue DATE,
NameofBook VARCHAR2(100),
Status VARCHAR2(50)
);

CREATE TABLE Fine (


Roll_no NUMBER,
Date DATE,
Amt NUMBER
);

-- Sample PL/ block to calculate and store fines


DECLARE
v_roll_no NUMBER;
v_name_of_book VARCHAR2(100);
v_issue_date DATE;
v_current_date DATE := SYSDATE;
v_fine_amt NUMBER;
v_days_late NUMBER;
BEGIN
-- Accept input from the user
v_roll_no := &roll_no; -- Input: Roll number
v_name_of_book := '&name_of_book'; -- Input: Name of the book

-- Retrieve the issue date from the Borrower table


SELECT DateofIssue INTO v_issue_date
FROM Borrower
WHERE Roll_no = v_roll_no AND NameofBook = v_name_of_book;

-- Calculate the number of days late


v_days_late := v_current_date - v_issue_date;

-- Check if the fine conditions are met (between 15 and 30 days late)
IF v_days_late >= 15 AND v_days_late <= 30 THEN
-- Calculate the fine amount (Rs 5 per day)
v_fine_amt := v_days_late * 5;

-- Insert the fine details into the Fine table


INSERT INTO Fine (Roll_no, Date, Amt)
VALUES (v_roll_no, v_current_date, v_fine_amt);

DBMS_OUTPUT.PUT_LINE('Fine details inserted into the Fine table:');


DBMS_OUTPUT.PUT_LINE('Roll_no: ' || v_roll_no);
DBMS_OUTPUT.PUT_LINE('Fine Amount: Rs ' || v_fine_amt);
ELSE
DBMS_OUTPUT.PUT_LINE('No fine is applicable for this book.');
END IF;

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Book not found for the given Roll number and Name of Book.');
END;
/
In this PL/ block, we:

1. Accept the roll_no and name_of_book from the user.


2. Retrieve the DateofIssue from the Borrower table for the specified book and roll number.
3. Calculate the number of days late between the current date (v_current_date) and the issue date.
4. Check if the fine conditions are met (between 15 and 30 days late).
5. If the conditions are met, calculate the fine amount and insert the fine details into the Fine table.
6. Display a message indicating the fine details, if applicable.
This PL/ block assumes that the tables Borrower and Fine already exist and that the user inputs the roll_no and
name_of_book. You can run this block in an Oracle environment, and it will perform the specified tasks based on the
conditions. Adjust the table structures and error handling as needed to match your specific requirements.
23) Implement Basic queries.

1. Create table employee.

2. Insert 10 records in table.

3. Create a view emp_vl of table employee which has emp_id , name and dept-attributes.
4. Display name and department of employee working in Manager or Marketing department

5. Display employees who were hired earliest or latest.

6. Display name and department no of employees who are manager, market analysts. Use Predicates

7. List employees hired in August.

8. List employees who are hired after 31/12/2006.

Question 23

To perform the basic queries you've mentioned, you can follow these steps:

1. Create a table named "employee" with the necessary columns (emp_id, name, dept, and other attributes).

CREATE TABLE employee (

emp_id INT PRIMARY KEY,

name VARCHAR(50),

dept VARCHAR(50),

hire_date DATE

-- Add other attributes as needed

);

2. Insert 10 records into the "employee" table.

You can use INSERT statements to insert 10 records into the "employee" table. Here's an example of how to insert a few records:

INSERT INTO employee (emp_id, name, dept, hire_date)

VALUES

(1, 'John', 'Sales', '2022-01-15'),

(2, 'Alice', 'Marketing', '2021-12-10'),

-- Add more records as needed

(10, 'Eve', 'Manager', '2023-03-05');

3. Create a view named "emp_vl" that contains emp_id, name, and dept attributes from the "employee" table.
CREATE VIEW emp_vl AS

SELECT emp_id, name, dept

FROM employee;

4. Display the name and department of employees working in the Manager or Marketing department.

SELECT name, dept

FROM employee

WHERE dept IN ('Manager', 'Marketing');

5. Display employees who were hired earliest or latest.

-- Earliest hired employees

SELECT name, hire_date

FROM employee

WHERE hire_date = (SELECT MIN(hire_date) FROM employee);

-- Latest hired employees

SELECT name, hire_date

FROM employee

WHERE hire_date = (SELECT MAX(hire_date) FROM employee);

6. Display the name and department number of employees who are managers or market analysts using predicates.

SELECT name, dept

FROM employee

WHERE dept LIKE 'Manager' OR dept LIKE 'Marketing Analyst';

7. List employees hired in August.


SELECT name, hire_date

FROM employee

WHERE EXTRACT(MONTH FROM hire_date) = 8;

8. List employees who were hired after December 31, 2006.

SELECT name, hire_date

FROM employee

WHERE hire_date > '2006-12-31';

Please adapt the above queries to your specific data and requirements.
24) ) Indexing and join: Consider the relation

employee (emp_id,e_name,salary ,Date of Joining,Dapt_no,Designation)

Customer(c_id, c_name , email , city , pincode)Orders(Order_id , date , amount , cust_id.

a. create empid as primary key and indices on table employee.

b. create user defined index on any column

c. create sequence using auo-increment.

d. truncate table.

e. find list of customers who placed Orders and details of their Orderss.

f. find info of customers and append Orders details to the table/

g. list down customers who haven’t placed Orders.

Question 24
In the scenario provided, it seems like you're working with two tables, "employee" and "Customer," and you
want to perform various actions including indexing, joining, and data manipulation. Let's go through each
step:

a. To create an index on the "employee" table, you can use the following command to create an index on the
"emp_id" column, making it the primary key:

CREATE TABLE employee (


emp_id INT PRIMARY KEY,
e_name VARCHAR(255),
salary DECIMAL(10, 2),
Date_of_Joining DATE,
Dept_no INT,
Designation VARCHAR(255)
);

b. To create a user-defined index on a specific column, you can use the CREATE INDEX statement. For
example, to create an index on the "salary" column, you can use:

CREATE INDEX salary_index ON employee (salary);


c. To create a sequence using auto-increment, you can use the CREATE SEQUENCE statement. For
example, to create a sequence for generating unique customer IDs:

CREATE SEQUENCE customer_id_seq START WITH 1 INCREMENT BY 1;

d. To truncate a table, use the TRUNCATE TABLE statement. For example, to truncate the "employee"
table:

TRUNCATE TABLE employee;

e. To find a list of customers who placed Orderss and details of their Orderss, you can use a query with a
JOIN between the "Customer" and "Orders" tables. This query retrieves customer information and their
Orders details:

SELECT c.c_name, o.Order_id, o.date, o.amount


FROM Customer c
JOIN Orders o ON c.c_id = o.cust_id;

f. To find information about customers and append their Orders details to the table, you can use an INSERT
INTO...SELECT statement. This example inserts the results of the previous query into a new table:

CREATE TABLE CustomerOrderss AS


SELECT c.c_name, o.Order_id, o.date, o.amount
FROM Customer c
JOIN Orders o ON c.c_id = o.cust_id;

g. To list customers who haven't placed Orderss, you can use a LEFT JOIN between the "Customer" and
"Orders" tables and filter for rows where there's no match in the "Orders" table:
SELECT c.c_name
FROM Customer c
LEFT JOIN Orders o ON c.c_id = o.cust_id
WHERE o.cust_id IS NULL;

This query returns a list of customers who exist in the "Customer" table but don't have corresponding
records in the "Orders" table, indicating they haven't placed Orderss.
Make sure to adjust table and column names as needed to match your specific database schema.
25) Implement aggregation and indexing with suitable example in mongodb.

*Question 25*
Aggregation and indexing are important features in MongoDB that can improve query performance and
allow for complex data transformations. Let's explore both concepts with suitable examples.
*Aggregation in MongoDB:*

Aggregation in MongoDB allows you to perform data transformation and analysis on your data. You can use
the aggregation pipeline to process documents in various stages, applying filters, transformations, and
calculations. Here's an example of using aggregation to calculate the average salary of employees by
department:

// Sample employees collection


db.employees.insertMany([
{ name: "Alice", department: "HR", salary: 55000 },
{ name: "Bob", department: "IT", salary: 65000 },
{ name: "Charlie", department: "IT", salary: 75000 },
// Add more employee records
]);

// Use aggregation to calculate the average salary by department


db.employees.aggregate([
{
$group: {
_id: "$department",
avgSalary: { $avg: "$salary" }
}
}
]);
In this example, the aggregation pipeline groups employees by the "department" field and calculates the
average salary within each department.

*Indexing in MongoDB:*
Indexing in MongoDB can significantly improve query performance. By creating indexes on fields
frequently used for filtering and sorting, you can speed up query execution. Here's an example of creating an
index on the "name" field of the "employees" collection:

// Create an index on the "name" field


db.employees.createIndex({ name: 1 });

In this example, we create a single-field index on the "name" field, which will make name-based queries
faster. The 1 specifies that the index is in ascending Orders.
You can also create compound indexes on multiple fields, which can further optimize queries with multiple
filtering criteria.

// Create a compound index on "department" and "salary" fields


db.employees.createIndex({ department: 1, salary: -1 });

In this example, we create a compound index on "department" in ascending Orders and "salary" in
descending Orders.
Aggregation and indexing are powerful tools in MongoDB, and using them effectively can greatly enhance
the performance and capabilities of your database queries.

You might also like