DBMS LAB MANUAL(BCS403)
INTRODUCTION TO SQL
Pronounced as SEQUEL: Structured English QUERY Language
Pure non-procedural query language
Designed and developed by IBM, Implemented by Oracle
1978 System/R IBM- 1st Relational DBMS
1979 Oracle and Ingres
1982 SQL/DS and DB2 IBM
Accepted by both ANSI + ISO as Standard Query Language for any RDBMS
SQL86 (SQL1) : first by ANSI and ratified by ISO (SQL-87), minor revision on 89 (SQL-89)
SQL92 (SQL2) : major revision
SQL99 (SQL3) : add recursive query, trigger, some OO features, and non-scholar type
SQL2003 : XML, Window functions, and sequences (Not free)Supports all the three
sublanguages of DBMS: DDL, DML, DCL
Supports Aggregate functions, String Manipulation functions, Set theory operations, Date
Manipulation functions, rich set of operators ( IN, BETWEEN, LIKE, IS NULL,EXISTS)
Supports REPORT writing features and Forms for designing GUI based applications
DATA DEFINITION, CONSTRAINTS, AND SCHEMA CHANGES
Used to CREATE, ALTER, and DROP the descriptions of the database tables (relations)
Data Definition in SQL
CREATE, ALTER and DROP
table…………………………………….……relation
row……………………………………..…….tuple
column………………………………….……attribute
DATA TYPES
Numeric: NUMBER, NUMBER(s,p), INTEGER, INT, FLOAT, DECIMAL
Character: CHAR(n), VARCHAR(n), VARCHAR2(n), CHAR VARYING(n)
Bit String: BLOB, CLOB
Boolean: true, false, and null
Date and Time: DATE (YYYY-MM-DD) TIME( HH:MM:SS)
Timestamp: DATE + TIME
USER Defined types
CREATE SCHEMA
Specifies a new database schema by giving it a name
Ex: CREATE SCHEMA COMPANY AUTHORIZATION Jsmith;
CREATE TABLE
Specifies a new base relation by giving it a name, and specifying each of its attributes
and their data types
Syntax of CREATE Command:
CREATE TABLE <table name> ( <Attribute A1> <Data Type D1> [< Constarints>],
<Attribute A2> <Data Type D2> [< Constarints>],
…….
<Attribute An> <Data Type Dn> [< Constarints>],
[<integrity-constraint1>, <integrity-constraint k> ] );
- A constraint NOT NULL may be specified on
an attribute A constraint NOT NULL may be specified
on an attribute
Ex: CREATE TABLE DEPARTMENT (
DNAME VARCHAR(10) NOT NULL,
DNUMBER INTEGER NOT NULL,
MGRSSN CHAR(9), MGRSTARTDATE CHAR(9) );
DROP TABLE
Used to remove a relation (base table) and its definition.
The relation can no longer be used in queries, updates, or any other commands since its
description no longer exists
Example: DROP TABLE DEPENDENT;
ALTER TABLE:
Used to add an attribute to/from one of the base relations drop constraint -- The new attribute
will have NULLs in all the tuples of the relation right after the command is executed; hence,
the NOT NULL constraint is not allowed for such an attribute.
Example: ALTER TABLE EMPLOYEE ADD JOB VARCHAR2 (12);
The database users must still enter a value for the new attribute JOB for each EMPLOYEE
tuple. This can be done using the UPDATE command.
DROP A COLUMN (AN ATTRIBUTE)
ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS CASCADE; All constraints
and views that reference the column are dropped automatically, along with the column.
ALTER TABLE COMPANY.EMPLOYEE DROP ADDRESS RESTRICT; Successful if no
views or constraints reference the column. ALTER TABLE COMPANY.DEPARTMENT
ALTER MGRSSN DROP DEFAULT;
EX: ALTER TABLE COMPANY.DEPARTMENT ALTER MGRSSN SET DEFAULT
“333445555”;
LAB EXPERIMENTS
Program 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 any three records in the employee table containing 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:
Step 1: Creating a user and granting permissions
Login as UN:System
PW: System
>CREATE USER UName IDENTIFIED BY passwd;
Output: User UName created.
>GRANT ALL PRIVILEGES to UName;
Output: Grant succeeded.
Logout from System Admin.
Again, Login with new Username and Password, what you have created.
UN: UName
PW: passwd
Step 2: Creating the Employee table
>CREATE TABLE Employee1
( EMPNO INT,
ENAME VARCHAR(20),
JOB VARCHAR(20),
MANAGER_NO INT,
SAL DECIMAL(10,2),
COMMISSION DECIMAL(10,2)
);
Output: Table EMPLOYEE1 created.
>desc Employee1;
Output:(Check for all columns and their data types)
Step 3: Inserting three records and rolling back
BEGIN
INSERT INTO Employee1 VALUES(1, 'John Doe', 'Manager', NULL, 50000.00, 1000.00);
INSERT INTO Employee1 VALUES(2, 'Jane Smith', 'Developer', 1, 40000.00, 500.00);
INSERT INTO Employee1 VALUES(3, 'Alice Johnson', 'Analyst', 1, 35000.00, NULL);
END;
Output:
3 rows inserted.
>commit;
Output: Commit complete.
>select * from Employee1;
>delete from Employee1 where ename = 'John Doe';
Output: 1 row deleted.
>select * from employee1;
Output:
rollback;
Output: Rollback complete.
select * from employee1;
Output:
Step 4: Adding primary key and not null constraints
Syntax for adding PK constraint:
ALTER TABLE Table_Name ADD CONSTRAINT Constraint_Name PRIMARY KEY
(Column_Name);
> ALTER TABLE Employee1 ADD CONSTRAINT PK PRIMARY KEY (EMPNO);
Output:
Table EMPLOYEE1 altered.
Syntax for adding NotNull constraint:
ALTER TABLE T_NAME MODIFY C_NAME NOT NULL;
>ALTER TABLE employee1 MODIFY ename varchar(20) NOT NULL;
Output:
Table EMPLOYEE1 altered.
Step 5: Inserting null values and verifying the result
INSERT INTO Employee1 VALUES (1, 'Test Employee', 'Tester', 1, 35000.00,
1000.00);
ERROR
Violation of PK constraint.
INSERT INTO Employee1 VALUES (4, NULL , 'Tester', 1, 35000.00, 1000.00);
ERROR
Cannot insert NULL to Ename
Program 2:
Create a table called Employee that contains attributes EMPNO,ENAME,JOB,
MGR,SAL & execute the following.
1. Add a column commission with domain to the Employee table.
2. Insert any five records into the table.
3. Update the column details of job
4. Rename the column of the Employee table using the alter command.
5. Delete the employee whose Empno is 105.
Solution:
Step 1:
>CREATE TABLE Employee2 (
EMPNO INT PRIMARY KEY,
ENAME VARCHAR(50),
JOB VARCHAR(10),
MGR INT,
SAL DECIMAL(10, 2));
Output: Table Employee created
>Desc Employee2;
Output:
Step 2: Add a column commission with domain to the Employee table.
Syntax: Alter table Tname Add Colname datatype;
>ALTER TABLE Employee2 ADD commission DECIMAL(10, 2);
Output: Employee table altered.
>Desc Employee2;
Output:
Step 3: Insert five records into the table
>INSERT INTO Employee2 VALUEs(101, 'John Doe', 'Manager', NULL, 5000.00,
200.00);
INSERT INTO Employee2 VALUEs(102, 'Jane Smith', 'Developer', 101, 4000.00,
150.00)
INSERT INTO Employee2 VALUEs(103, 'Alice Johnson', 'Designer', 101, 3500.00,
100.00)
INSERT INTO Employee2 VALUEs(104, 'Bob Brown', 'Analyst', 102, 4500.00, 180.00);
INSERT INTO Employee2 VALUEs(105, 'Emma Davis', 'Tester', 103, 3800.00,
120.00);
Output: 5 rows inserted
>Select * from Employee2;
Output:
Step 4: Update the column 'JOB' details
Example: John Doe previous job role was Manager, now changed to Software
Engineer
>UPDATE Employee2
SET JOB = 'S/w Engnr'
WHERE ENAME = 'John Doe';
Output: Employee table updated
>Select * from Employee2
Output:
Step 5:Rename the column of the Employee table using the alter command.
Syntax:
ALTER TABLE table_name RENAME COLUMN old_column_name TO
new_column_name;
>ALTER TABLE Employee2 RENAME COLUMN Ename TO Empname;
Output: Table Altered
>Desc Employee2;
Output:
Step 6:Delete the employee whose Empno is 105.
>DELETE FROM Employee WHERE EMPNO = 105;
Output: 1 row deleted
Display the records after deletion
>SELECT * FROM Employee;
Output:
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:
Step 1: Creating the Employee3 table
>CREATE TABLE Employee3 (
E_id INT PRIMARY KEY,
E_name VARCHAR(50),
Age INT,
Salary DECIMAL(10, 2));
Output:
Table Employee created
Insertion of Values into the Table:
Insert into Employee3 values (1, 'Ramesh', 35, 25000.00);
Insert into Employee3 values (2,'Suresh', 39, 32000.00);
Insert into Employee3 values (3,'Ganesh', 50, 55000.00);
Insert into Employee3 values (4,'Sunaina',45, 24000.00);
Insert into Employee3 values (5,'Rashmi', 41, 66000.00);
Step 2. Count number of employee names
>SELECT COUNT(E_name) AS TotalEmployees FROM Employee3;
Output:
Step 3. Find the Maximum age:
>SELECT MAX(Age) AS MaxAge FROM Employee3;
Output:
Step 4. Find the Minimum age
>SELECT MIN(Age) AS MinAge FROM Employee3;
Output:
Step 5. Find salaries of employees in Ascending Order:
>SELECT Salary FROM Employee3 ORDER BY Salary ASC;
Output:
Step 6. Find grouped salaries of employees:
>SELECT Salary, COUNT(*) AS EmployeeCount
FROM Employee3
GROUP BY Salary;
Output:
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.
CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY)
Solution:
Step 1: Create and insert values into customers table
-- Create the CUSTOMERS table
>CREATE TABLE CUSTOMERS (
ID INT PRIMARY KEY,
NAME VARCHAR(100),
AGE INT,
ADDRESS VARCHAR(255),
SALARY DECIMAL(10, 2)
);
Output:
Table created;
Begin
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (1,
'John Doe', 30, '123 Main St', 50000);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (2,
'Jane Smith', 35, '100 WashingtonDC', 75000);
INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (3,
'Alice', 25, '104 Sanfransisco', 75000);
end;
Output:
Statement processed;
select * from customers;
Step 2: Creating a Trigger
>
CREATE OR REPLACE TRIGGER salary_difference_trigger
BEFORE INSERT OR UPDATE OR DELETE ON CUSTOMERS
FOR EACH ROW
DECLARE
old_salary NUMBER;
new_salary NUMBER;
BEGIN
IF INSERTING OR UPDATING THEN
old_salary := NVL(:OLD.SALARY, 0);
new_salary := NVL(:NEW.SALARY, 0);
DBMS_OUTPUT.PUT_LINE('Salary difference: ' || (new_salary - old_salary));
ELSIF DELETING THEN
old_salary := NVL(:OLD.SALARY, 0);
DBMS_OUTPUT.PUT_LINE('Salary before deletion: ' || old_salary);
END IF;
END;
Output:
Trigger created;
Step 3: Check the working of trigger on Update
>UPDATE CUSTOMERS
SET SALARY=90000
Where ID=2;
Output:
Salary difference: 15000
1 row(s) updated.
select * from customers;
Step 4: Check the working of trigger on Insert
>INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS, SALARY) VALUES (4,
'James Bond', 40, '121 california', 58000);
output:
Salary difference: 58000
1 row(s) inserted.
select * from customers;
Step 5: Check the working of trigger on Delete
>delete from customers
where id=4;
output:
Salary before deletion: 58000
1 row(s) deleted.
select * from customers;
5. Create a cursor for the Employee table & extract the values from the table.
Declare the variables,Open the cursor & extract the values from the cursor.
Close the cursor. Employee(E_id,E_name, Age, Salary)
Solution:
STEP1: Create table Employee
CREATE TABLE Employee (
E_id INT,
E_name VARCHAR(255),
Age INT,
Salary DECIMAL(10, 2)
);
OUTPUT:
Table created
STEP 2:Insert values into Employee table:
BEGIN
INSERT INTO Employee VALUES(1, 'Samarth', 30, 50000.00);
INSERT INTO Employee VALUES(2, 'Ramesh Kumar', 25, 45000.00);
INSERT INTO Employee VALUES (3, 'Seema Banu', 35, 62000.00);
INSERT INTO Employee VALUES (4, 'Dennis Anil', 28, 52000.00);
INSERT INTO Employee VALUES (5, 'Rehman Khan', 32, 58000.00);
END;
OUTPUT:
Statement Processed.
STEP 3: Create a procedure
CREATE OR REPLACE PROCEDURE fetch_employee_data
IS
emp_id Employee.E_id%TYPE;
emp_name Employee.E_name%TYPE;
emp_age Employee.Age%TYPE;
emp_salary Employee.Salary%TYPE;
CURSOR emp_cursor IS
SELECT E_id, E_name, Age, Salary
FROM Employee;
BEGIN
OPEN emp_cursor;
LOOP
FETCH emp_cursor INTO emp_id, emp_name, emp_age, emp_salary;
EXIT WHEN emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_id || ', Name: ' || emp_name
|| ', Age: ' || emp_age || ', Salary: ' || emp_salary);
END LOOP;
CLOSE emp_cursor;
END;
/
OUTPUT:
Procedure created.
STEP 4: Run the procedure
BEGIN
fetch_employee_data;
END;
OUTPUT:
Employee ID: 1, Name: Samarth, Age: 30, Salary: 50000
Employee ID: 2, Name: Ramesh Kumar, Age: 25, Salary: 45000
Employee ID: 3, Name: Seema Banu, Age: 35, Salary: 62000
Employee ID: 4, Name: Dennis Anil, Age: 28, Salary: 52000
Employee ID: 5, Name: Rehman Khan, Age: 32, Salary: 58000
Statement processed.
Program 6
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.
Step 1: First, let’s create the N_RollCall and O_RollCall tables with similar structure:
CREATE TABLE N_RollCall (
student_id INT PRIMARY KEY,
student_name VARCHAR(255),
birth_date DATE
);
OUTPUT:
Table created
CREATE TABLE O_RollCall (
student_id INT PRIMARY KEY,
student_name VARCHAR(255),
birth_date DATE
);
OUTPUT:
Table created
Step 2: Add Sample Records to both tables
(date format: MM-DD-YYYY)
Begin
INSERT INTO O_RollCall VALUES (1,'Shivanna','08-15-1995');
INSERT INTO O_RollCall VALUES (3,'Cheluva','12-10-1990');
end;
OUTPUT:
Statement Processed.
Select * from O_Rollcall;
Begin
INSERT INTO N_RollCall VALUES(1, 'Shivanna', '08-15-1995');
INSERT INTO N_RollCall VALUES(2, 'Bhadramma','03-22-1998');
INSERT INTO N_RollCall VALUES(3, 'Cheluva', '12-10-1990');
INSERT INTO N_RollCall VALUES(4, 'Devendra', '05-18-2000');
INSERT INTO N_RollCall VALUES(5, 'Eshwar', '09-03-1997');
end;
OUTPUT:
Statement Processed.
Select * from N_Rollcall;
OUTPUT:
Step 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:
CREATE OR REPLACE PROCEDURE merge_rollcall_data AS
-- Declare variables
n_id N_RollCall.student_id%TYPE;
n_name N_RollCall.student_name%TYPE;
n_birth_date N_RollCall.birth_date%TYPE;
v_count NUMBER;
-- Cursor declaration
CURSOR n_cursor IS
SELECT student_id, student_name, birth_date
FROM N_RollCall;
BEGIN
-- Open the cursor
OPEN n_cursor;
-- Start looping through cursor results
LOOP
-- Fetch data from cursor into variables
FETCH n_cursor INTO n_id, n_name, n_birth_date;
-- Exit loop if no more rows to fetch
EXIT WHEN n_cursor%NOTFOUND;
-- Check if the data already exists in O_RollCall
SELECT COUNT(*)
INTO v_count
FROM O_RollCall
WHERE student_id = n_id;
IF v_count = 0 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 merge_rollcall_data;
/
OUTPUT:
Procedure created.
Step 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:
Begin
merge_rollcall_data;
End;
OUTPUT:
Statement Processed.
Step 5: Verify Records in O_RollCall
select * from O_rollcall;
Program 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
Setting Up MongoDB on Ubuntu
Learn how to install and configure MongoDB on Ubuntu step-by-step to power your
application’s database. This comprehensive guide covers everything from installation
and service setup to basic configuration and optional security measures. By following
these instructions, you’ll have MongoDB up and running smoothly on your Ubuntu
machine, ready to support your application’s data needs efficiently and securely.
Setting up MongoDB on Ubuntu involves several steps including installation,
configuration, and basic setup. Below are step-by-step instructions for setting up
MongoDB on Ubuntu. This installation was carried out on Ubuntu 22.04.4 LTS(should
work for the newer versions as well).
Install MongoDB Community Edition
1. Import the public key used by the package management system
From a terminal, install gnupg and curl if they are not already available:
sudo apt-get install gnupg curl
To import the MongoDB public GPG key, run the following command:
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
--dearmor
2. Create a list file for MongoDB
Create the /etc/apt/sources.list.d/mongodb-org-7.0.list file for Ubuntu 22.04
(Jammy):
echo "deb [ arch=amd64,arm64
signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ]
https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo
tee /etc/apt/sources.list.d/mongodb-org-7.0.list
3. Reload local package database
sudo apt-get update
4. Install the MongoDB packages
sudo apt-get install -y mongodb-org
5. Install the MongoDB Compass (GUI Optional)
Easily explore and manipulate your database with Compass, the GUI for MongoDB.
Intuitive and flexible, Compass provides detailed schema visualizations, real-time
performance metrics, sophisticated querying abilities, and much more.
sudo apt-get install -y mongodb-org
Run MongoDB Community Edition
1. Start MongoDB.
sudo systemctl start mongod
2. Verify that MongoDB has started successfully.
sudo systemctl status mongod
This should display similar output as shown below
$ sudo systemctl status mongod
[sudo] password for putta:
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor pres>
Active: active (running) since Wed 2024-05-08 12:54:07 IST; 1h 56min ago
Docs: https://docs.mongodb.org/manual
Main PID: 275211 (mongod)
Memory: 78.6M
CPU: 31.213s
CGroup: /system.slice/mongod.service
└─275211 /usr/bin/mongod --config /etc/mongod.conf
May 08 12:54:07 putta-PowerEdge-T30 systemd[1]: Started MongoDB Database
Serv>
May 08 12:54:07 putta-PowerEdge-T30 mongod[275211]: {"t":{"$date":"2024-05-08>
lines 1-12/12 (END)
3. Stop MongoDB. (Optional)
sudo systemctl stop mongod
4. Restart MongoDB. (Optional)
sudo systemctl restart mongod
5. Begin using MongoDB.
Mongosh
Now you will see a MongoDB shell, where you can issue the queries. If you have
reached here, it means that you have successfully installed MongoDB on your
system.
Lab program
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.
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>show dbs
—-
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")
Output:
{ok:1 }
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:
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
])
Output:
acknowledged: true,
insertedIds: {
'0': ObjectId('668228977c76971b7bcc8988'),
'1': ObjectId('668228977c76971b7bcc8989'),
'2': ObjectId('668228977c76971b7bcc898a'),
'3': ObjectId('668228977c76971b7bcc898b'),
'4': ObjectId('668228977c76971b7bcc898c')
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
})
Output:
acknowledged: true,
insertedId: ObjectId('668228c57c76971b7bcc898d')
6. Read (Query) Operations
a. Find All Documents
To retrieve all documents from the ProgrammingBooks collection:
bookDB> db.ProgrammingBooks.find().pretty()
Output:
_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
To find books published after the year 2000:
bookDB> db.ProgrammingBooks.find({ year: { $gt: 2000 } }).pretty()
Output:
_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)" } }
Output:
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
//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'),
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" } }
Output:
{
acknowledged: true,
insertedId: null,
matchedCount: 5,
modifiedCount: 5,
upsertedCount: 0
//verify the update operation by displaying books published before year 2010
bookDB> db.ProgrammingBooks.find({ year: { $lt: 2010 } }).pretty()
Output:
_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'),
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" })
Output:
{ acknowledged: true, deletedCount: 1 }
You can check whether the specified document is deleted by displaying the contents
of the collection.
bookDB> db.ProgrammingBooks.find().pretty()
Output:
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 } })
Output:
{ acknowledged: true, deletedCount: 2 }
You can check whether the specified documents were deleted by displaying the
contents of the collection.
bookDB> db.ProgrammingBooks.find().pretty()
Output:
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({})
Output:
{ acknowledged: true, deletedCount: 3 }
//verify by displaying the collection
bookDB> db.ProgrammingBooks.find().pretty()
9. Delete the Collection Using drop():
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>
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.