0% found this document useful (0 votes)
5 views22 pages

DBMS Manual

The document provides a comprehensive guide on managing a database using MySQL, including creating tables, inserting records, and applying constraints. It covers various SQL operations such as transactions, triggers, and cursors, along with examples for each operation. Additionally, it demonstrates the use of aggregate functions and stored procedures to manipulate and query data effectively.

Uploaded by

shravyacs062
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

DBMS Manual

The document provides a comprehensive guide on managing a database using MySQL, including creating tables, inserting records, and applying constraints. It covers various SQL operations such as transactions, triggers, and cursors, along with examples for each operation. Additionally, it demonstrates the use of aggregate functions and stored procedures to manipulate and query data effectively.

Uploaded by

shravyacs062
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Database Management Systems BCS403

1. Create a table called Employee & execute the following. Employee


(EMPNO, ENAME, JOB, MANAGER_NO, SAL, COMMISSION)
1. Create a user and grant all permissions to the user.
2. Insert the any three records in the employee table contains attributes
EMPNO, ENAME JOB, MANAGER_NO, SAL, COMMISSION and
use rollback. Check the result.
3. Add primary key constraint and not null constraint to the employee
table.
4. Insert null values to the employee table and verify the result.

Solution:

Login with the root account as shown below. Create a


database COMPANY and switch to it using the USE command.

$ sudo mysql -u root

mysql> CREATE DATABASE COMPANY;


Query OK, 1 row affected (0.14 sec)

mysql> USE COMPANY;


Database changed

Creating the Employee Table


Within the Database COMPANY create a table Employee as follows. Use the SHOW
TABLES; command to confirm that the table was indeed created.

mysql> CREATE TABLE COMPANY.Employee (


-> EMPNO INT,
-> ENAME VARCHAR(255),
-> JOB VARCHAR(255),
-> MANAGER_NO INT,
-> SAL DECIMAL(10, 2),
-> COMMISSION DECIMAL(10, 2)
-> );

mysql> SHOW TABLES;

Verify the structure of this newly created Employee table using the DESC command.
mysql> DESC COMPANY.Employee;

Create a User and Grant Permissions

mysql> CREATE USER IF NOT EXISTS 'dbuser' IDENTIFIED BY '12345';


mysql> GRANT ALL PRIVILEGES ON COMPANY.Employee TO 'dbuser'; $ mysql
-u dbuser -p
Enter password: 12345

Prof. Suma H C, Dept of CSE Page 1 of 22


Database Management Systems BCS403

Welcome to the MySQL monitor. Commands end with ; or \g.


Your MySQL connection id is 11
Server version: 8.0.37 MySQL Community Server - GPL

Copyright (c) 2000, 2024, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its


affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
Now logout and login with the new account credentials. Press Ctrl+D to logout.
Command to login with new user account is shown below.

Now we have successfully logged with our new account. Change the current
database to COMPANY database using USE command. Now we will illustrate
how to insert records and also the COMMIT and ROLLBACK facilities.
mysql> USE COMPANY;

Database changed

mysql> SELECT * FROM Employee;

mysql> START TRANSACTION;

mysql> INSERT INTO Employee VALUES (1, Suma HC', 'Manager', NULL, 5000.00,
1000.00);

COMMIT DATABASE, db CONTENTS ARE WRITTEN TO THE DISK

mysql> COMMIT;

TO DISPLAY TABLE CONTENTS

mysql> SELECT * FROM Employee;

START ANOTHER TRANSACTION


mysql> START TRANSACTION;

mysql> INSERT INTO VALUES (2, 'Riya Singh’, 'Developer', 1, 4000.00, NULL);

mysql> INSERT INTO Employee VALUES (3, 'Hema Shree', 'Salesperson', 2, 3000.00,
500.00);

mysql> SELECT * FROM Employee;

Prof. Suma H C, Dept of CSE Page 2 of 22


Database Management Systems BCS403

mysql> DELETE FROM Employee where ENAME = ‘Suma HC';


Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM Employee;

ROLLBACK 2 INSERTS AND 1 DELETE OPERATIONS


mysql> ROLLBACK;

mysql> SELECT * FROM Employee;

ADDING CONSTRAINTS
ADD PRIMARY KEY CONSTRAINT

Add Primary Key Constraint


mysql> ALTER TABLE Employee
-> ADD CONSTRAINT pk_employee PRIMARY KEY (EMPNO);

verify primary key constraint


mysql> DESC Employee;

mysql> INSERT INTO Employee VALUES (1, 'Ranjan', 'Manager', NULL, 5000.00,
1000.00);

ADD NOT NULL CONSTRAINT

Add Not Null Constraints


mysql> ALTER TABLE Employee
-> MODIFY ENAME VARCHAR(255) NOT NULL,
-> MODIFY JOB VARCHAR(255) NOT NULL,
-> MODIFY SAL DECIMAL(10, 2) NOT NULL;

mysql> INSERT INTO Employee VALUES (4, 'Ranjan', 'Manager', NULL, 5000.00,
1000.00);

mysql>
mysql> SELECT * FROM Employee;

mysql> INSERT INTO Employee VALUES (NULL, 'Tester', NULL, 3500.00,


NULL);
ERROR 1048 (23000): Column 'ENAME' cannot be null

We just illustrated as to how to add not null constraint to the Employee table. We see
that the first insert doesn’t violate null constraint, however the second insert does
violate null constraint as ENAME field cannot be null.

Prof. Suma H C, Dept of CSE Page 3 of 22


Database Management Systems BCS403

2. Create a table called Employee that contain attributes


EMPNO,ENAME,JOB, MGR,SAL &
execute the following.
1. Add a column commission with domain to the Employeetable.
2. Insert any five records into the table.
3. Update the column details of job
4. Rename the column of Employ table using alter command.
5. Delete the employee whose Empno is 201.

Solution
Creating the Employee Table

mysql> CREATE DATABASE COMPANY02;

mysql> USE COMPANY02;


Database changed

mysql> CREATE TABLE Employee (


-> EMPNO INT,
-> ENAME VARCHAR(255),
-> JOB VARCHAR(255),
-> MGR INT,
-> SAL DECIMAL(10, 2)
-> );

mysql> SHOW TABLES;

mysql> DESC Employee;

Adding a Column (Commission) to the Employee Table

mysql> ALTER TABLE Employee


-> ADD COLUMN COMMISSION DECIMAL(10, 2);
mysql> DESC Employee;

We have added a column COMMISSION using the ALTER command, which is


shown above.

Inserting 5 Records into the Employee Table

mysql> INSERT INTO Employee VALUES


(201, 'Ravi Kumar', 'Manager', NULL, 5000.00, 1000.00),
(202, 'Sita Devi', 'Developer', 201, 4000.00, NULL),
(203, 'Rahul Das', 'Salesperson', 202, 3000.00, 500.00),
(204, 'John Paul', 'Accountant', 201, 4500.00, NULL),
(205, 'Mina Roy', 'HR Manager', 201, 4800.00, 800.00);

Prof. Suma H C, Dept of CSE Page 4 of 22


Database Management Systems BCS403

mysql> SELECT * FROM Employee;

Updating Column Details (JOB) in the Employee Table

mysql> UPDATE Employee


-> SET JOB = 'Senior Developer'
-> WHERE EMPNO = 201;

mysql> SELECT * FROM Employee;

Renaming a Column in the Employee Table

To rename the MGR column to MANAGER_ID:

mysql> ALTER TABLE Employee


-> CHANGE COLUMN MGR MANAGER_ID INT;

mysql> DESC Employee;

Deleting a Specific Employee (EMPNO = 205) from the Employee Table

mysql> DELETE FROM Employee


-> WHERE EMPNO = 205;

mysql> SELECT * FROM Employee;

Prof. Suma H C, Dept of CSE Page 5 of 22


Database Management Systems BCS403

3. Queries using aggregate


functions(COUNT,AVG,MIN,MAX,SUM),Group by,Orderby.
Employee(E_id, E_name, Age, Salary)
1. Create Employee table containing all Records E_id, E_name, Age,
Salary.
2. Count number of employee names from Employee table
3. Find the Maximum age from Employee table.
4. Find the Minimum age from Employee table.
5. Find salaries of employee in Ascending Order.
6. Find grouped salaries of employees.

Solution
1. Creating the Employee Table

mysql> CREATE DATABASE COMPANY03;

mysql> USE COMPANY03;


Database changed
mysql> CREATE TABLE Employee (
-> E_id INT PRIMARY KEY,
-> E_name VARCHAR(255),
-> Age INT,
-> Salary DECIMAL(10, 2)
-> );

mysql> DESC Employee;

2. Populating the Employee Table with 12 Records

mysql> INSERT INTO Employee (E_id, E_name, Age, Salary)


-> VALUES
(1, 'Amit', 22, 30000.00),
(2, 'Neha', 24, 32000.00),
(3, 'Raj', 23, 31000.00),
(4, 'Tina', 25, 33000.00),
(5, 'Vijay', 26, 34000.00),
(6, 'Anu', 28, 36000.00),
(7, 'Kiran', 27, 35000.00),
(8, 'Meena', 29, 37000.00),
(9, 'Ravi', 30, 38000.00),
(10, 'Pooja', 21, 29000.00),
(11, 'Suresh', 31, 39000.00),
(12, 'Lata', 32, 40000.00);
mysql> SELECT * FROM Employee;

Prof. Suma H C, Dept of CSE Page 6 of 22


Database Management Systems BCS403

3. Count Number of Employee Names

mysql> SELECT COUNT(E_name) AS TotalEmployees


-> FROM Employee;

4. Find the Maximum Age

mysql> SELECT MAX(Age) AS MaxAge


-> FROM Employee;

5. Find the Minimum Age

mysql> SELECT MIN(Age) AS MinAge


-> FROM Employee;

6. Find Salaries of Employees in Ascending Order

mysql> SELECT E_name, Salary


-> FROM Employee
-> ORDER BY Salary ASC;

7. Find Grouped Salaries of Employees


mysql> SELECT Salary, COUNT(*) AS EmployeeCount
-> FROM Employee
-> GROUP BY Salary;

In these queries:
• COUNT(E_name) counts the number of non-NULL values in the E_name column.
• MAX(Age) finds the maximum age among the employees.
• MIN(Age) finds the minimum age among the employees.
• ORDER BY Salary ASC sorts the employees based on their salaries in ascending
order.
• GROUP BY Salary groups employees by their salaries and counts the number of
employees for each salary.

Prof. Suma H C, Dept of CSE Page 7 of 22


Database Management Systems BCS403

4. Create a row level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the
CUSTOMERS table. This trigger will display the salary difference between
the old & new Salary.

CREATE TABLE CUSTOMERS (


ID INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(255),
AGE INT,
ADDRESS VARCHAR(255),
SALARY DECIMAL(10, 2),
MESSAGE VARCHAR(255) DEFAULT NULL
);

-- INSERT TRIGGER
DELIMITER //

CREATE TRIGGER after_insert_salary_difference


AFTER INSERT ON CUSTOMERS
FOR EACH ROW
BEGIN
SET @my_sal_diff = CONCAT('salary inserted is ', NEW.SALARY);
END;//

DELIMITER ;

-- UPDATE TRIGGER
DELIMITER //

CREATE TRIGGER after_update_salary_difference


AFTER UPDATE ON CUSTOMERS
FOR EACH ROW
BEGIN
DECLARE old_salary DECIMAL(10, 2);
DECLARE new_salary DECIMAL(10, 2);

SET old_salary = OLD.SALARY;


SET new_salary = NEW.SALARY;
SET @my_sal_diff = CONCAT('salary difference after update is ',
NEW.SALARY - OLD.SALARY);
END;//

DELIMITER ;

-- DELETE TRIGGER
DELIMITER //

CREATE TRIGGER after_delete_salary_difference


AFTER DELETE ON CUSTOMERS

Prof. Suma H C, Dept of CSE Page 8 of 22


Database Management Systems BCS403

FOR EACH ROW


BEGIN
SET @my_sal_diff = CONCAT('salary deleted is ', OLD.SALARY);
END;//

DELIMITER ;

-- test INSERT TRIGGER


INSERT INTO CUSTOMERS VALUES (SUMA, 30, 'mysore', 50000.00);

SELECT @my_sal_diff AS SAL_DIFF;

-- test UPDATE TRIGGER


UPDATE CUSTOMERS
SET SALARY = 55000.00
WHERE ID = 1;

SELECT @my_sal_diff AS SAL_DIFF;

-- test DELETE TRIGGER


DELETE FROM CUSTOMERS
WHERE ID = 1;

SELECT @my_sal_diff AS SAL_DIFF;

Prof. Suma H C, Dept of CSE Page 9 of 22


Database Management Systems BCS403

5. Create cursor for Employee table & extract the values from the table.
Declare the variables,Open the cursor & extract the values from the cursor.
Close the cursor.
CUSTOMERS(ID,NAME,AGE,ADDRESS,SALARY)

1. Creating the Employee Table and insert few records


CREATE DATABASE COMPANY05;

USE COMPANY05;

CREATE TABLE Employee (


E_id INT,
E_name VARCHAR(255),
Age INT,
Salary DECIMAL(10, 2)
);

INSERT INTO Employee VALUES


INSERT INTO Employee VALUES
(1, 'Amit', 22, 30000.00),
(2, 'Neha', 24, 32000.00),
(3, 'Ravi', 26, 34000.00),
(4, 'Pooja', 23, 31000.00),
(5, 'Suman', 25, 33000.00);

2. Create a Stored Procedure with Cursor


To create a cursor for the Employee table, extract values using the cursor, and
then close the cursor in MySQL, you’ll need to use stored procedures that support
cursor operations.

DELIMITER //

CREATE PROCEDURE fetch_employee_data()


BEGIN
-- Declare variables to store cursor values
DECLARE emp_id INT;
DECLARE emp_name VARCHAR(255);
DECLARE emp_age INT;
DECLARE emp_salary DECIMAL(10, 2);

-- Declare a cursor for the Employee table


DECLARE emp_cursor CURSOR FOR
SELECT E_id, E_name, Age, Salary
FROM Employee;

-- Declare a continue handler for the cursor


DECLARE CONTINUE HANDLER FOR NOT FOUND

Prof. Suma H C, Dept of CSE Page 10 of 22


Database Management Systems BCS403

SET @finished = 1;

-- Open the cursor


OPEN emp_cursor;

-- Initialize a variable to control cursor loop


SET @finished = 0;

-- Loop through the cursor results


cursor_loop: LOOP
-- Fetch the next row from the cursor into variables
FETCH emp_cursor INTO emp_id, emp_name, emp_age, emp_salary;

-- Check if no more rows to fetch


IF @finished = 1 THEN
LEAVE cursor_loop;
END IF;

-- Output or process each row (for demonstration, print the values)


SELECT CONCAT('Employee ID: ', emp_id, ', Name: ', emp_name, ', Age: ', emp_age, ',
Salary: ', emp_salary) AS Employee_Info;
END LOOP;

-- Close the cursor


CLOSE emp_cursor;
END//

DELIMITER ;

In this stored procedure (fetch_employee_data):


• We declare variables (emp_id, emp_name, emp_age, emp_salary) to store values
retrieved from the cursor.
• A cursor (emp_cursor) is declared to select E_id, E_name, Age, and Salary from
the Employee table.
• We declare a continue handler (CONTINUE HANDLER) for NOT
FOUND condition to handle the end of cursor data.
• The cursor is opened (OPEN emp_cursor), and a loop (cursor_loop) is used to fetch
each row from the cursor.
• We fetch values into the variables and process them within the loop (for demonstration,
we print the values using a SELECT statement).
• The loop continues until all rows are fetched (@finished = 1).
• Finally, the cursor is closed (CLOSE emp_cursor).

Prof. Suma H C, Dept of CSE Page 11 of 22


Database Management Systems BCS403

3. Execute the Stored Procedure


Once the stored procedure fetch_employee_data is created, you can execute it to fetch and
process data from the Employee table:

mysql> CALL fetch_employee_data();


+----------------------------------------------------------+
| Employee_Info |
+----------------------------------------------------------+
| Employee ID: 1, Name: Samarth, Age: 30, Salary: 50000.00 |
+----------------------------------------------------------+
1 row in set (0.07 sec)
+---------------------------------------------------------------+
| Employee_Info |
+---------------------------------------------------------------+
| Employee ID: 2, Name: Ramesh Kumar, Age: 25, Salary: 45000.00 |
+---------------------------------------------------------------+
1 row in set (0.07 sec)
+-------------------------------------------------------------+
| Employee_Info |
+-------------------------------------------------------------+
| Employee ID: 3, Name: Seema Banu, Age: 35, Salary: 62000.00 |
+-------------------------------------------------------------+
1 row in set (0.07 sec)
+--------------------------------------------------------------+
| Employee_Info |
+--------------------------------------------------------------+
| Employee ID: 4, Name: Dennis Anil, Age: 28, Salary: 52000.00 |
+--------------------------------------------------------------+
1 row in set (0.07 sec)
+--------------------------------------------------------------+
| Employee_Info |
+--------------------------------------------------------------+
| Employee ID: 5, Name: Rehman Khan, Age: 32, Salary: 58000.00 |
+--------------------------------------------------------------+
1 row in set (0.07 sec)

• The stored procedure fetch_employee_data declares variables


(emp_id, emp_name, emp_age, emp_salary) to store values retrieved from the
cursor.
• A cursor (emp_cursor) is declared for the Employee table to
select E_id, E_name, Age, and Salary.
• The cursor is opened (OPEN emp_cursor), and the FETCH statement retrieves the
first row from the cursor into the declared variables.
• A WHILE loop processes each row fetched by the cursor (SQLSTATE() =
'00000' checks for successful fetching).
• Within the loop, you can perform operations or output the values of each row.
• The CLOSE statement closes the cursor after processing all rows.
This example demonstrates how to create and use a cursor in MySQL to extract values from
the Employee table row by row. Adjust the cursor query and processing logic based on your
table structure and desired operations.

Prof. Suma H C, Dept of CSE Page 12 of 22


Database Management Systems BCS403

7.Write a PL/SQL block of code using parameterized 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.

Solution
To accomplish this task in MySQL, we can use a stored procedure with a parameterized cursor
to merge data from one table (N_RollCall) into another table (O_RollCall) while skipping
existing data. We’ll iterate through the records of N_RollCall and insert them
into O_RollCall only if they do not already exist.
1. Create the Tables
First, let’s create the N_RollCall and O_RollCall tables with similar structure:

CREATE DATABASE ROLLCALL;

USE ROLLCALL;

-- Create N_RollCall table


CREATE TABLE N_RollCall (
student_id INT PRIMARY KEY,
student_name VARCHAR(255),
birth_date DATE
);

-- Create O_RollCall table with common data


CREATE TABLE O_RollCall (
student_id INT PRIMARY KEY,
student_name VARCHAR(255),
birth_date DATE
);

2. Add Sample Records to both tables


Let’s insert some sample data into the O_RollCall table:

mysql> -- Insert common data into O_RollCall


mysql> INSERT INTO O_RollCall (student_id, student_name, birth_date)
-> VALUES
-> (1, 'Shivanna', '1995-08-15'),
-> (3, 'Cheluva', '1990-12-10');
Query OK, 2 rows affected (0.17 sec)
Records: 2 Duplicates: 0 Warnings: 0

Prof. Suma H C, Dept of CSE Page 13 of 22


Database Management Systems BCS403

Let’s insert some sample data into the N_RollCall table, including records that are common
with O_RollCall:

mysql> -- Insert sample records into N_RollCall


mysql> INSERT INTO N_RollCall (student_id, student_name, birth_date)
-> VALUES
-> (1, 'Shivanna', '1995-08-15'), -- Common record with O_RollCall
-> (2, 'Bhadramma', '1998-03-22'),
-> (3, 'Cheluva', '1990-12-10'), -- Common record with O_RollCall
-> (4, 'Devendra', '2000-05-18'),
-> (5, 'Eshwar', '1997-09-03');
Query OK, 5 rows affected (0.21 sec)
Records: 5 Duplicates: 0 Warnings: 0

3. Define the Stored Procedure


Next, let’s define the merge_rollcall_data stored procedure to merge records
from N_RollCall into O_RollCall, skipping existing records:

DELIMITER //

CREATE PROCEDURE merge_rollcall_data()


BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE n_id INT;
DECLARE n_name VARCHAR(255);
DECLARE n_birth_date DATE;

-- Declare cursor for N_RollCall table


DECLARE n_cursor CURSOR FOR
SELECT student_id, student_name, birth_date
FROM N_RollCall;

-- Declare handler for cursor


DECLARE CONTINUE HANDLER FOR NOT FOUND
SET done = TRUE;

-- Open the cursor


OPEN n_cursor;

-- Start looping through cursor results


cursor_loop: LOOP
-- Fetch data from cursor into variables
FETCH n_cursor INTO n_id, n_name, n_birth_date;

-- Check if no more rows to fetch


IF done THEN
LEAVE cursor_loop;
END IF;

Prof. Suma H C, Dept of CSE Page 14 of 22


Database Management Systems BCS403

-- Check if the data already exists in O_RollCall


IF NOT EXISTS (
SELECT 1
FROM O_RollCall
WHERE student_id = n_id
) THEN
-- Insert the record into O_RollCall
INSERT INTO O_RollCall (student_id, student_name, birth_date)
VALUES (n_id, n_name, n_birth_date);
END IF;
END LOOP;

-- Close the cursor


CLOSE n_cursor;
END//

DELIMITER ;
• The stored procedure merge_rollcall_data uses a cursor (n_cursor) to iterate through
the records of the N_RollCall table.
• Inside the cursor loop (cursor_loop), each record (n_id, n_name, n_date)
from N_RollCall is fetched and checked against the O_RollCall table.
• If the record does not already exist in O_RollCall (checked using NOT EXISTS), it is
inserted into O_RollCall.
• The cursor loop continues until all records from N_RollCall have been processed.
• The cursor is then closed (CLOSE n_cursor).

4. Execute the Stored Procedure


Finally, execute the merge_rollcall_data stored procedure to merge records
from N_RollCall into O_RollCall while skipping existing records:

mysql> CALL merge_rollcall_data();


Query OK, 0 rows affected (0.87 sec)

5. Verify Records in O_RollCall


After executing the procedure, verify the records in the O_RollCall table to confirm that new
records from N_RollCall have been inserted, while existing common records have been
skipped:

mysql> -- Select all records from O_RollCall


mysql> SELECT * FROM O_RollCall;

Prof. Suma H C, Dept of CSE Page 15 of 22


Database Management Systems BCS403

7. Install an Open Source NoSQL Data base MongoDB & perform


basic CRUD(Create, Read, Update & Delete) operations. Execute MongoDB
basic Queries using CRUD operations.
Solution
1. Installing Open Source NoSQL Data base MongoDB

Please refer to the blog below which contains detailed procedure of installing Open Source
NoSQL Data base MongoDB.

https://moodle.sit.ac.in/blog/setting-up-mongodb-on-ubuntu/

2. Perform basic CRUD(Create, Read, Update & Delete) operations.


1. Start MongoDB.
Launch the MongoDB daemon using the following command:

sudo systemctl start mongod

2. Start the MongoDB Shell


Launch the MongoDB shell to perform basic CRUD operations.

Mongosh

3. Switch to a Database (Optional):


If you want to use a specific database, switch to that database using the use command. If the
database doesn’t exist, MongoDB will create it implicitly when you insert data into it:

test> use bookDB


switched to db bookDB
bookDB>

4. Create the ProgrammingBooks Collection:


To create the ProgrammingBooks collection, use the createCollection() method. This step is
optional because MongoDB will automatically create the collection when you insert data into
it, but you can explicitly create it if needed:

bookDB> db.createCollection("ProgrammingBooks")
This command will create an empty ProgrammingBooks collection in the current database
(bookDB).
5. INSERT operations
a. Insert 5 Documents into the ProgrammingBooks Collection :
Now, insert 5 documents representing programming books into
the ProgrammingBooks collection using the insertMany() method:

Prof. Suma H C, Dept of CSE Page 16 of 22


Database Management Systems BCS403

bookDB> db.ProgrammingBooks.insertMany([
{
title: "Clean Code: A Handbook of Agile Software Craftsmanship",
author: "Robert C. Martin",
category: "Software Development",
year: 2008
},
{
title: "JavaScript: The Good Parts",
author: "Douglas Crockford",
category: "JavaScript",
year: 2008
},
{
title: "Design Patterns: Elements of Reusable Object-Oriented Software",
author: "Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides",
category: "Software Design",
year: 1994
},
{
title: "Introduction to Algorithms",
author: "Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein",
category: "Algorithms",
year: 1990
},
{
title: "Python Crash Course: A Hands-On, Project-Based Introduction to Programming",
author: "Eric Matthes",
category: "Python",
year: 2015
}
])

b. Insert a Single Document into ProgrammingBooks:


Use the insertOne() method to insert a new document into
the ProgrammingBooks collection:

bookDB> db.ProgrammingBooks.insertOne({
title: "The Pragmatic Programmer: Your Journey to Mastery",
author: "David Thomas, Andrew Hunt",
category: "Software Development",
year: 1999
})

Prof. Suma H C, Dept of CSE Page 17 of 22


Database Management Systems BCS403

6. Read (Query) Operations


a. Find All Documents
To retrieve all documents from the ProgrammingBooks collection:

bookDB> db.ProgrammingBooks.find().pretty()
[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin',
category: 'Software Development',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e0'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e1'),
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
author: 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides',
category: 'Software Design',
year: 1994
},
{
_id: ObjectId('663eaaebae582498972202e2'),
title: 'Introduction to Algorithms',
author: 'Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein',
category: 'Algorithms',
year: 1990
},
{
_id: ObjectId('663eaaebae582498972202e3'),
title: 'Python Crash Course: A Hands-On, Project-Based Introduction to Programming',
author: 'Eric Matthes',
category: 'Python',
year: 2015
},
{
_id: ObjectId('663eab05ae582498972202e4'),
title: 'The Pragmatic Programmer: Your Journey to Mastery',
author: 'David Thomas, Andrew Hunt',
category: 'Software Development', year: 1999 } ]
b. Find Documents Matching a Condition

Prof. Suma H C, Dept of CSE Page 18 of 22


Database Management Systems BCS403

To find books published after the year 2000:

bookDB> db.ProgrammingBooks.find({ year: { $gt: 2000 } }).pretty()


[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin',
category: 'Software Development',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e0'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e3'),
title: 'Python Crash Course: A Hands-On, Project-Based Introduction to Programming',
author: 'Eric Matthes',
category: 'Python',
year: 2015
}
]

7. Update Operations
a. Update a Single Document
To update a specific book (e.g., change the author of a book):

bookDB>db.ProgrammingBooks.updateOne(
{ title: "Clean Code: A Handbook of Agile Software Craftsmanship" },
{ $set: { author: "Robert C. Martin (Uncle Bob)" } }
)

//verify by displaying books published in year 2008


bookDB> db.ProgrammingBooks.find({ year: { $eq: 2008 } }).pretty()
[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin (Uncle Bob)',
category: 'Software Development',
year: 2008 }, {
_id: ObjectId('663eaaebae582498972202e0'),

Prof. Suma H C, Dept of CSE Page 19 of 22


Database Management Systems BCS403

title: 'JavaScript: The Good Parts',


author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
}
]

b. Update Multiple Documents


To update multiple books (e.g., update the category of books published before 2010):

bookDB> db.ProgrammingBooks.updateMany(
{ year: { $lt: 2010 } },
{ $set: { category: "Classic Programming Books" } }
)

//verify the update operation by displaying books published before year 2010
bookDB> db.ProgrammingBooks.find({ year: { $lt: 2010 } }).pretty()
[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin (Uncle Bob)',
category: 'Classic Programming Books',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e0'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'Classic Programming Books',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e1'),
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
author: 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides',
category: 'Classic Programming Books',
year: 1994
},
{
_id: ObjectId('663eaaebae582498972202e2'),
title: 'Introduction to Algorithms',
author: 'Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein',
category: 'Classic Programming Books',
year: 1990 }, {
_id: ObjectId('663eab05ae582498972202e4'),

Prof. Suma H C, Dept of CSE Page 20 of 22


Database Management Systems BCS403

title: 'The Pragmatic Programmer: Your Journey to Mastery',


author: 'David Thomas, Andrew Hunt',
category: 'Classic Programming Books',
year: 1999
}
]

8. Delete Operations
a. Delete a Single Document
To delete a specific book from the collection (e.g., delete a book by title):

bookDB> db.ProgrammingBooks.deleteOne({ title: "JavaScript: The Good Parts" })


{ acknowledged: true, deletedCount: 1 }

You can check whether the specified document is deleted by displaying the contents of the
collection.
b. Delete Multiple Documents
To delete multiple books based on a condition (e.g., delete all books published before 1995):

bookDB> db.ProgrammingBooks.deleteMany({ year: { $lt: 1995 } })


{ acknowledged: true, deletedCount: 2 }

bookDB> db.ProgrammingBooks.deleteMany({ year: { $lt: 1995 } })


{ acknowledged: true, deletedCount: 2 }

You can check whether the specified documents were deleted by displaying the contents of the
collection.
c. Delete All Documents in the Collection:
To delete all documents in a collection (e.g., ProgrammingBooks), use
the deleteMany() method with an empty filter {}:

//delete all documents in a collection


bookDB> db.ProgrammingBooks.deleteMany({})
{ acknowledged: true, deletedCount: 3 }

//verify by displaying the collection


bookDB> db.ProgrammingBooks.find().pretty()

9. Delete the Collection Using drop():

Prof. Suma H C, Dept of CSE Page 21 of 22


Database Management Systems BCS403

To delete a collection named ProgrammingBooks, use the drop() method with the name of
the collection:

bookDB> show collections


ProgrammingBooks

bookDB> db.ProgrammingBooks.drop()
true

bookDB> show collections

bookDB>

bookDB> show collections


ProgrammingBooks

bookDB> db.ProgrammingBooks.drop()
true

bookDB> show collections

bookDB>

The command db.ProgrammingBooks.drop( ) will permanently delete


the ProgrammingBooks collection from the current database (bookDB).
After deleting the collection, you can verify that it no longer exists by listing all collections in
the database using the command show collections.

Prof. Suma H C, Dept of CSE Page 22 of 22

You might also like