Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

All Assignments

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

Assignment 1

Database Assignment 1
Note : Use Emp, dept and salgrade table

1.To list all records with sal > 2000 and comm>200
 select * from emp
-> where sal > 2000 and comm > 200;

2. To list all record with job=’Clerk’ or sal>2000


select * from emp
-> where job='CLERK' or sal > 2000;

3.To list all the record with sal=1250 or 1100 or 2850


 select * from emp
-> where sal in(1100,1250,2850);

4. To list all employees with sal>1250 and <2850


 select * from emp
-> where sal > 1250 and sal < 2850;

5.To list all employees with name ends with AS


 select * from emp
-> where ename like '%AS';

6. To list all employees with job starts with C and ends with K
 select * from emp
-> where job like
-> 'C%' and job like '%K';

7. To list all employees with job contains L at third position and M at third
last position
 select * from emp
-> where job like
-> '__L%' and job like '%M__';
8.To list all the record with sal not equal to 1250 or 1100 or 2850
 select * from emp
-> where sal not in(1100, 1250, 2850);

9.To list all employees with salnot >1250 and <2850


 select * from emp
-> where sal not between 1250 and 2850;

10. To list all employees with job starts with C , E at 3rd position and ends with
K
 select * from emp
-> where job like
-> 'C_E%K';

To list all rows with comm is null


11.
 select * from emp
-> where comm is null;

To list all employees with comm is null and name starts with ‘S’
12.
 select * from emp
-> where comm is null
-> and ename like 'S%';
To list all employees with job contains 5 characters
13.
 select * from emp
-> where job like '_____';

14. To list all employees with name contain ‘A’ at 1 position and job Contains
5 characters
 select * from emp
-> where job REGEXP '^A.{4}';
Assignment 2
Q2. Solve the following
1. Retrieve the details (Name, Salary and dept no) of the emp who
are working in department code 20, 30 and 40.
 select * from emp
where deptno in(20,30,40);

2. Display the total salary of all employees . Total salary will be


calculated as sal+comm+sal*0.10
 select ename, job, sal,
sal+ifnull(comm, 0)+sal*0.10 'Total Salary'
from emp;

3. List the Name and job of the emp who have joined before 1 jan
1986 and whose salary range is between 1200and 2500. Display
the columns with user defined Column headers.
 select ename, hiredate, job, sal
-> from emp
-> where hiredate < '1986-01-01'
-> and (sal between 1200 and 1500);
4. List the empno, name, and department number of the emp
works under manager with id 7698
 select ename, empno, deptno
-> from emp
-> where mgr = 7698;

5. List the name, job, and salary of the emp who are working in
departments 10 and 30.
 select ename, job, sal
-> from emp
-> where deptno in(10,30);
6. Display name concatenated with dept code separated by comma
and space. Name the column as ‘Emp info’.
select concat(ename,' , ',job) 'Emp Info'
-> from emp;
7. Display the emp details who do not have manager.
 select * from emp
-> where mgr is null;

8. Write a query which will display name, department no and date


of joining of all employee who were joined January 1, 1981 and
March 31, 1983. Sort it based on date of joining (ascending).
select ename,deptno,hiredate from emp where hiredate
between '1981-1-1' and '1983-3-31' order by hiredate
 select ename, deptno, hiredate
-> from emp
-> where hiredate between
-> '1981-01-01' and '1983-03-31'
-> order by hiredate;
9. Display the employee details where the job contains word ‘AGE’
anywhere in the Job
 select ename, job
-> from emp
-> where job like '%AGE%';

Or
 select ename, job
-> from emp
-> where job REGEXP '^.*AGE.*$';

11. List the details of the employee , whose names start with ‘A’ and
end with ‘S’ or whose names contains N as the second or third
character, and ending with either ‘N’ or ‘S’.
select * from emp where ename like ‘A%S’ or ename like ‘_N%N’ or
ename like ‘_N%S’ or ename like ‘__N%N’ or ename like ‘__N%S’ or
select * from emp where ename REGEXP ‘^A.*S$| ^..?N.*[NS]$‘
 select ename
-> from emp
-> where ename REGEXP '^A.*S$|^..?N.*[NS]$';

12. List the names of the emp having ‘_’ character in their name.
 select ename
-> from emp
-> where ename REGEXP '^[_]$';

13. find 3rd highly paid employee


 select ename, sal
-> from emp
-> order by sal desc
-> limit 1 offset 2;

14. find employee who has earned highest commission


 select ename, comm
-> from emp
-> order by comm desc
-> limit 1;
15. display ascii value of 1st character of job from emp
 select ename, job, ascii(job) 'ASCII Value of Job'
-> from emp;

16. display empno,ename,job,code code should be 1 st 3 characters of


ename and 1 st 3 characters of job
 select substr(ename,1,3) 'Emp name', substr(job,1,3) 'Job', empno
-> from emp;
Single Row functions

1. To list all employees and their email, to generate email use 2 to 5


characters from ename Concat it with 2 to 4 characters in job and
then concat it with ‘@mycompany.com’
 select ename, lower(concat(substr(ename, 2, 3), substr(job, 2,
2), '@mycompany.com'))
-> from emp;
2. List all employees who joined in September.
 select ename, hiredate
-> from emp
-> where month(hiredate)=9;

3. List the empno, name, and department number of the emp who
have experience of 18 or more years and sort them based on their
experience.
 select ename, empno, deptno, sal,
-> year(curdate())- year(hiredate) 'Experience'
-> from emp
-> where year(curdate())- year(hiredate) > 18
-> order by sal;

4. Display the employee details who joined on 3rd of any month or


any year
select * from emp
-> where month(hiredate)=3;

5. display all employees who joined between years 1981 to 1983.


 select ename, hiredate
-> from emp
-> where year(hiredate) >= 1981 and year(hiredate) <= 1983;
Or
select ename, hiredate
-> from emp
-> where year(hiredate) between 1981 and 1983;
Assignment 3
Group functions

1. Display the Highest, Lowest, Total & Average salary of all employee. Label
the columns Maximum, Minimum, Total and Average respectively for each
Department. Also round the result to the nearest whole number.
 select round(max(sal),2) 'Maximum', round(min(sal),2)
'Minimum',round(sum(sal),2) 'Total Salary', round(avg(sal),2) 'Average Salary'
-> from emp;

2. Display Department no and number of managers working in that


department. Label the column as ‘Total Number of Managers’ for each
department.
 select deptno, count(*) 'Total no of Managers'
-> from emp
-> where job='manager'
-> group by deptno;

3. Get the Department number, and sum of Salary of all non managers where
the sum is greater than 20000.
 select deptno, sum(sal)
-> from emp
-> where job !='manager'
-> group by deptno
-> having sum(sal) > 20000;

4. display employee name, deparmentname and sum of sal


departmentwise,count number of employees in each department
 select deptno,sum(sal) 'Total Salary of dept',
-> count(*) 'No of Employees'
-> from emp
-> group by job;

create following table and answer the questions


1. create table product to store
(pid,pname,qty,amount,company) insert 7 rows in
product table;
a. display total amount and total quantity sold for each company
 select amount * qty 'Total Amount' ,
-> qty 'Total Qty', company
-> from product;

b. display how many products are there for each company


select company, count(*) 'No of Products'
-> from product
-> group by pname;
c. display pname,company and total amount for each company
 select company, pname, amount*qty 'Total Amount'
-> from product;

d. display average amount for each product


select pname, amount 'Average Amount'
-> from product;
display company names,product name and average amount for
e.
productwise
 select company, pname, amount 'Average Amount'
-> from product;

Date and Time functions

1. Write a query to display the first day of the month (in datetime format) three months before the
current month.
Sample current date : 2014-09-03
Expected result : 2014-06-01

 select date_sub(date_add(last_day(now()), interval 1 day), interval 3 month);


2. Write a query to display the last day of the month (in datetime format) three months before the
current month.

 select date_sub(last_day(now()), interval 3 month);

3. Write a query to get the distinct Mondays from hiredate in emp tables.

 select distinct hiredate

-> from emp

-> where dayname(hiredate)= 'Mondays';

4. Write a query to get the first day of the current year.

5. Write a query to get the last day of the current year.

6. Write a query to calculate your age in year.

 select sum(year(curdate()) - 1997);


d

7. Write a query to get the current date in the following format.


Sample date : 04-sep-2014
Output : September 4, 2014

==> select date_format(curdate(),'%M ' '%d' ',' ' %Y');

8. Write a query to get the current date in Thursday September 2014 format. Thursday September
2014

==> select date_format(curdate(), '%W ' '%M ' '%Y');

9. Write a query to extract the year from the current date.


 select extract(year from curdate()) 'Year of Current Date';

10. Write a query to get the first name and hire date from employees table where hire date between
'1987-06-01' and '1987-07-30'

 select ename, hiredate

-> from emp

-> where hiredate between '1987-06-01' and '1987-07-30';

11. Write a query to display the current date in the following format. Sample output: Thursday 4th
September 2014 00:00:00

==>select date_format(curdate(),'%W ' '%D ' '%M ' '%Y ' '%T');
12. Write a query to display the current date in the following format. Sample output: 05/09/2014

==> select date_format(curdate(),'%d' "/" '%m' "/" '%Y');

13. Write a query to display the current date in the following format. Sample output: 12:00 AM Sep
5, 2014

==> select date_format(curdate(), '%r ' '%M ' ', ' '%Y');

14. Write a query to get the employees who joined in the month of June.

 select ename, hiredate

-> from emp

-> where monthname(hiredate) = 'june';


15. Write a query to get the years in which more than 10 employees joined.

 select year(hiredate), count(*) 'No of Employess joined'

-> from emp

-> group by year(hiredate)

-> having count(*) >= 10;

16. Write a query to get first name of employees who joined in 1987.

 select * from emp

-> where year(hiredate)=1987;

17. Write a query to get employees whose experience is more than 5 years.

 select ename

-> from emp

-> where year(curdate())-year(hiredate) > 5;


18. Write a query to get employee ID, last name, and date of first salary of the employees.

select ename, empno, date_add(last_day(hiredate), interval 1 day) 'Date of First Salary'

-> from emp;

19. Write a query to get first name, hire date and experience of the employees.

 select ename, hiredate, year(curdate())-year(hiredate) 'Experience'

-> from emp;


Sample table: employees

20. Write a query to get the department ID, year, and number of employees joined.

 select deptno, year(hiredate), count(*) 'No of employees joined'

-> from emp

-> group by deptno;

31. Practice creating following tables

create table mydept_DBDA

deptid int primary key,

dname varchar(20) not null unique,

dloc varchar(20)
)

insert into mydept_DBDA values(30,'Purchase','Mumbai');

create table myemployee

empno number(5) primary key,

fname varchar2(15) not null,

mname varchar2(15),

lname varchar2(15) not null,

sal number(9,2) check(sal >=1000),

doj date default sysdate,

passportnum varchar2(15) unique,

deptno number constraint fk_deptno references mydept_DBDA(deptid) on delete


cascade

34. Solve following using alter table


add primary key constraint on emp,dept,salgrade

emp ---- empno

 alter table empbackup


-> add primary key(empno);

dept--- deptno

salgrade---

grade

add foreign key

constarint in emp

deptno --->>

dept(deptno)

add new column in emp table netsal with constraint default 1000

35.Update employee sal increase sal of each employee by 15 % sal


+comm, change the job
to manager and mgr to 7777 for all employees in deptno 10.
36.change job of smith to senior clerk
 update emp
-> set job='sr clerk'
-> where ename = 'smith';
37. increase salary of all employees by 15% if they are earning some
commission
38.list all employees with sal>smith's sal
 select ename, sal from emp
-> where sal > (select sal from emp where
-> ename='smith');

39.list all employees who are working in smith's department


 select ename, deptno
-> from emp
-> where deptno=(select deptno from emp
-> where ename='smith');
40.list all employees with sal < martin's sal and salary > clark's sal
 select ename, empno, sal
-> from emp
-> where sal not between (select sal from emp where ename='martin')
-> and (select sal from emp where ename='clark');

41.delete all employees working in allen's department


 delete from emp
-> where deptno=(select deptno from(select * from emp) b
-> where b.ename='allen');

42.change salary of Allen to the salary of Miller.


 update emp
-> set sal = (select sal from (select sal,ename from emp) b where b.ename =
'miller')
-> where ename= 'allen';

43.change salary of all employees who working in allen's department


to the salary of Miller.
 update emp
set sal = (select sal from(select * from emp)b where b.ename = 'miller')
where deptno = (select deptno from (select * from emp) c where
c.ename='allen');

44.list all employees with salary > either Smith's salary or alan's sal
 select ename, sal from emp
-> where sal > (select sal from emp where ename='smith')
-> or sal > (select sal from emp where ename='allen');
45.list all employees who earn more than average sal of dept 10
 select ename, sal, deptno
-> from emp
-> where sal > (select avg(sal) from emp where deptno=10);

46.list all employees who earn more than average sal of Alan's
department
 select ename, sal
-> from emp
-> where sal > (select avg(sal) from emp
-> where deptno=(select deptno from emp where ename='allen'));
47.list all employees who are working in purchase department
 Empty set, no such a dept
48.list all employees who earn more than average salary of their own
department
 select ename, sal, deptno
-> from emp e
-> where sal > (select avg(sal) from emp b where b.deptno=e.deptno);

49.list all employees who earn sal < than their managers salary
 select ename, sal from emp w where w.sal< (
-> select sal from emp m where w.mgr=m.empno);
50.list all employees who are earning more than average salary of
their job
 select e.ename, e.sal, e.job from emp e, emp m
-> where e.sal > (select avg(sal) from emp m where m.job=e.job) and
m.ename=e.ename;

51.display employee name and department


 select ename, dname
-> from emp e, dept d
-> where e.deptno=d.deptno;
52.display empno,name,department name and grade (use emp,dept
and salgrade table)
 select e.empno, e.ename, d.dname
-> ,s.grade from emp e, dept d, salgrade s
-> where e.deptno=d.deptno and
-> e.sal between s.losal and s.hisal;
53.list all employees number,name, mgrno and manager name
 select e.empno, e.ename, e.mgr, m.empno 'Manager no', m.ename
-> 'Manager Name'
-> from emp e, emp m
-> where e.mgr=m.empno;
54.create following tables and solve following questions(primary
keys are marked in yellow) foreign keys are marked in green

product(pid,pname,price,qty,cid,sid)

salesman (sid,sname,address)

category(cid,cnam,descritpion)
i. list all product name,their category name and name of
a person, who sold that product
select pname, cname, sname
-> from product p, category c, salesman s
-> where p.cid=c.cid and p.sid=s.salesmanid;
ii. list all product name and salesman name for all
salesman who stays in pune

 select p.pname, s.sname, s.address


-> from product p right join salesman s
-> on s.address='Pune'
-> union
-> select p.pname, s.sname, s.address
-> from product p right join salesman s
-> on s.address='Pune';
iii. list all product name and category name
 select pname, cname
-> from product p, category c
-> where p.cid=c.cid;

55.create following tables and solve following questions(primary


keys are marked in yellow) foreign keys are marked in green

faculty(fid,fname,sp.skill1,sp.skill2)

courses(cid,cname,rid,fid)
room(roomid,rnam

e,rloc) faculty

fid fname spskill1 spskill2


10 kjzhcjhz a b
11 sdd x z
12 lksjk a x
13 ksdjlkj a b

courses
cid cname rid fid

121 DBDA 100


10
131 DAC 101
141 DTISS
151 DIOT 105
12

Room
roomid rname rloc

100 jasmin 1st


floor
101 Rose 2nd
floor
105 Lotus 1st
floor
103 Mogra 1st
floor
1. list all courses for which no room is assigned. And all
rooms for which are available

 select c.cid, c.cname, r.roomno, r.rname, r.rloc


-> from course c right join room r
-> on c.rid is null;

2. list all faculties who are not allocated to any course and
rooms which are not allocated to any course
 select f.fid, f.fname, r.roomno,r.rname
-> from faculty f join room r join course c
-> on c.fid is null or r.roomno not exists in (select t.rid
-> from course t);
3. list all rooms which are allocated or not allocated to any
courses
select * from room;

4.list all rooms which are not allocated to any courses


select r.roomno, r.rname from room r
-> where not exists(select rid from course where course.rid=r.roomno);
5.display courses and faculty assigned to those courses
whose special skill is database
6. display time table --- it should contain course details ,
faculty and room details
a. create following tables with given constraints
product- qty >0, default 20.00,pname not null and unique
prodid pname qty price catid sid

123 lays 30 30.00 1 12


111 pepsi 40 50.00 4 11
134 nachos 50 50.00 1 12
124 dairy milk 40 60.00 2 14
124 pringles 60.00 1 14
40

saleman ----- sname not null


sid sname city
11 Rahul Pune
12 Kirti Mumbai
13 Prasad Nashik
14 Arnav Amaravati

category ---- cname unique and

not null cid cname

description

1 chips very crunchy


2 chocolate very chocolaty
3 snacks yummy
4 cold drinks thanda thanda cool cool
1. List all products with category chips
2. display all products sold by kirti
3. display all salesman who do not sold any product
4. display all category for which no product is there
5. display all products with no category assigned
6. list all salesman who stays in city with name starts with P or N
7. add new column in salesman table by name credit limit

PL-SQL
Assignment
Solve the following

1. write a procedure to insert record into employee table.


the procedure should accept empno, ename, sal, job, hiredate as input parameter write
insert statement inside procedure insert_rec to add one record into table

create procedure insert_rec(peno int,pnm varchar(20),psal decimal(9,2),pjob


varchar(20),phiredate date) begin
insert into emp(empno,ename,sal,job,hiredate)
values(peno,pnm,psal,pjob,phiredate) end//

2. write a procedure to delete record from employee table. the procedure should accept
empno as input parameter.
write delete statement inside procedure delete_emp to delete one record from emp
table
 delimiter //
create procedure delete_emp(vempno int)
begin
delete from emp
where vempno = empno;
end //

3. write a procedure to display empno,ename,deptno,dname for all employees with sal


> given salary. pass salary as a parameter to procedure
 delimiter //
create procedure displayDa(vsal decimal(9,2))
begin
select ename, empno, deptno, dname
from emp, dept
where sal > vsal;
end //

4. write a procedure to find min,max,avg of salary and number of employees in the given
deptno.
deptno --→ in parameter
min,max,avg and count ---→ out type parameter
execute procedure and then display values min,max,avg and count
 delimiter //
create procedure minmax(vdeptno int, out vmin decimal(9,2),
out vmax decimal(9,2), out vavg decimal(9,2), out vcount int)
begin
select min(sal), max(sal), avg(sal), count(*)
from emp
where deptno = vdeptno;
end //

5. write a procedure to display all pid,pname,cid,cname and salesman name(use


product,category and salesman table)


6. write a procedure to display all vehicles bought by a customer. pass cutome name as a
parameter.(use vehicle,salesman,custome and relation table)
7. Write a procedure that displays the following information of all emp
Empno,Name,job,Salary,Status,deptno
Note: - Status will be (Greater, Lesser or Equal) respective to average salary of their own
department. Display an error message Emp table is empty if there is no matching record.

 delimiter //

create procedure displaystatusinfo()

begin

declare vstop,vcnt int default 0;

declare vempno,vdeptno int;

declare vsal,vavgsal decimal(9,2);

declare vjob varchar(20);

declare vename,vstatus varchar(20);

declare emp_cur cursor for select empno,ename,job,sal,deptno from emp;

declare continue handler for NOT FOUND set vstop=1;

open emp_cur;

label11:loop

fetch emp_cur into vempno,vename,vjob,vsal,vdeptno;

if vstop=1 then
if vcnt=0 then

select 'Table is empty';

end if;

leave label11;

end if;

set vcnt=vcnt+1;

select avg(sal) into vavgsal

from emp

where deptno=vdeptno;

if vsal<vavgsal then

set vstatus='lesser';

elseif vsal>vavgsal then

set vstatus='greater';

else

set vstatus='equal';

end if;

select vempno,vename,vsal,vavgsal,vdeptno,vstatus;

update emp

set status=vstatus

where empno=vempno;

end loop;

close emp_cur;

end//

call displaystatusinfo();
8. Write a procedure to update salary in emp table based on following rules.
Exp< =35 then no Update
Exp> 35 and <=38 then 20% of salary
Exp> 38 then 25% of salary

9. Write a procedure and a function.


Function: write a function to calculate number of years of experience of employee.(note:
pass hiredate as a parameter)

delimiter //
create function getexperience(phiredate date) returns int
begin
declare vexp int;
set vexp = floor(datediff(curdate(),phiredate)/365);
return vexp;
end //
Procedure: Capture the value returned by the above function to calculate the additional
allowance for the emp based on the experience.
Additional Allowance = Year of experience x 3000
Calculate the additional allowance

and store Empno, ename,Date of Joining, and Experience in years


and additional allowance in Emp_Allowance table.
create table
emp_allowance( empno int,
ename varchar(20), hiredate
date, experience int, allowance
decimal(9,2));

10. Write a function to compute the following. Function should take sal and hiredate as i/p
and return the cost to company.
DA = 15% Salary, HRA= 20% of Salary, TA= 8% of Salary.
Special Allowance will be decided based on the service in the company. < 1
Year Nil
>=1 Year< 2 Year 10% of Salary
>=2 Year< 4 Year 20% of Salary
>4 Year 30% of Salary
 SET GLOBAL log_bin_trust_function_creators = 1;
delimiter //
create function cost_to_company(vsal decimal(9,2), hiredate date) returns decimal(9,2)
begin
declare cost, spallow decimal(9,2);
declare vexp int;
set vexp = getexperience(hiredate);
set cost = 0.15 * vsal + 0.20 * vsal + 0.08 * vsal;
if vexp >= 1 and vexp <= 2
then
set spallow = 0.10 * vsal;
elseif
vexp >= 2 and vexp <= 4 then
set spallow = 0.20 * vsal;
elseif
vexp >= 4 then
set spallow = 0.30 * vsal;
end if;
set cost = cost + spallow + vsal;
return cost;
end //
11. Write query to display empno,ename,sal,cost to company for all employees(note:
use function written in question 10)
 select empno, ename, sal, cost_to_company(sal,hiredate)
from emp;

Q2. Write trigger


1. Write a trigger to store the old salary details in Emp _Back (Emp _Back has the same
structure as emp table without any
constraint) table.
(note :create emp_back table before writing trigger)
----- to create emp_back table

create table
emp_back( empno int,
ename varchar(20), oldsal
decimal(9,2),
newsal decimal(9,2)
)
(note :
execute procedure written in Q8 and
check the entries in EMP_back table after execution of the procedure)
delimiter //
create trigger update_emp after update on emp
for each row
begin
insert into emp_back values(OLD.empno,OLD.ename,OLD.sal,NEW.sal);
end//

2. Write a trigger which add entry in audit table when user tries to insert or delete records
in employee table store empno,name,username and date on which operation per-
formed and which action is done insert or delete. in emp_audit table. create table be-
fore writing trigger.
 create table emp_audit
(
empno int,
ename varchar(20),
username varchar(20),
chdate date,
action_type varchar(20)
);
 delimiter //
create trigger insert_emp after insert on emp
for each row
begin
insert into emp_audit values(NEW.empno,NEW.ename,user(),curdate(),'insert');
end //

delimiter //
create trigger delete_emp before delete on emp
for each row
begin
insert into emp_audit values(OLD.empno,OLD.ename,user(),curdate(),'delete');
end //
3. ); Create table vehicle_history. Write a trigger to store old vehicleprice and new vehicle
price in history table before you update price in vehicle table (note: use vehicle table).
create table

vehicle_history( vno int, vname

varchar(20), oldprice

decimal(9,2), newprice

decimal(9,2), chdate date,

username varchar(20)

);
MongoDb Day 1

1. Write a MongoDB query to display all the documents in the collection restaurants

db.restaurent.find().pretty()
2. Write a MongoDB query to display the fields restaurant_id, name, borough and cuisine for all the doc-
uments in the collection restaurant.

 db.restaurent.find({},{restaurent_id:1,name:1,borouugh:1,cuisine:1}).pretty()
3. Write a MongoDB query to display the fields restaurant_id, name, borough and cuisine, but exclude
the field _id for all the documents in the collection restaurant.

 db.restaurent.find({},{restaurent_id:1,name:1,borouugh:1,cuisine:1,_id:0}).pretty()
4. Write a MongoDB query to display the fields restaurant_id, name, borough and zip code, but exclude
the field _id for all the documents in the collection restaurant.

 db.restaurent.find({},{restaurent_id:1,name:1,borouugh:1,'address.zipcode':1,_id:0}).pretty()
5. Write a MongoDB query to display all the restaurant which is in the borough Bronx

 db.restaurent.find({borough:'Bronx'}).pretty()
6. Write a MongoDB query to display the first 5 restaurant which is in the borough Bronx.

 db.restaurent.find({borough:'Bronx'}).pretty().limit(5)
7.Write a MongoDB query to display the next 5 restaurants after skipping first 5 which are in the
borough Bronx.

 db.restaurent.find({borough:'Bronx'}).pretty().limit(5).skip(5)
8. Write a MongoDB query to find the restaurants who achieved a score more than 90.

 db.restaurent.find({grades:{$elemMatch:{score:{$gt:90}}}}).pretty()
9. Write a MongoDB query to find the restaurants that achieved a score, more than 80 but less than
100.

 db.restaurent.find({grades:{$elemMatch:{score:{$gt:80, $lt:100}}}}).pretty()
10. Write a MongoDB query to find the restaurants which locate in latitude value less than -
95.754168.

db.restaurent.find({'address.coord.1':{$lt:95.754168}}).pretty()
11. Write a MongoDB query to find the restaurants that do not prepare any cuisine of 'American' and
their grade score more than 70 and latitude less than -65.754168.

 db.restaurent.find({'address.coord.0':{$lt:-65.754168},cuisine:{$nin:['American']},'grades.score':
{$gt:70}}).pretty()
12. Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American' and
achieved a score more than 70 and located in the longitude less than 65.754168.
 db.restaurent.find({cuisine:{$nin:['American']}, 'grades.score':{$gt:70},'address.coord.1':
{$lt:65.754168}}).pretty()
13. Write a MongoDB query to find the restaurants which do not prepare any cuisine of 'American ' and
achieved a grade point 'A' not belongs to the borough Brooklyn. The document must be displayed
according to the cuisine in descending order.

db.restaurent.find({cuisine:{$nin:['American']}, 'grades.grade':'A', borough:'Brooklyn'}).pretty()


14. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which contain 'Wil' as first three letters for its name.

 db.restaurent.find({name:/^Wil.*$/},{restaurent_id:1,name:1,borough:1,cuisine:1,_id:0}).pretty()
15. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which contain 'ces' as last three letters for its name.
 db.restaurent.find({name:/^.*ces$/},{restaurent_id:1,name:1,borough:1,cuisine:1,_id:0}).pretty()

16. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which contain 'Reg' as three letters somewhere in its name.

 db.restaurent.find({name:/^.*Reg.*$/},{restaurent_id:1,name:1,borough:1,cuisine:1,_id:0}).pretty()
17. Write a MongoDB query to find the restaurants which belong to the borough Bronx and prepared ei-
ther American or Chinese dish.

 db.restaurent.find({borough:'Bronx',cuisine:{$in:['American','Chinese']}}).pretty()
18. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which belong to the borough Staten Island or Queens or Bronxor Brooklyn.

 db.restaurent.find({borough:{$in:['Staten Island','Queens','Bronx','Brooklyn']}},
{_id:0,address:0}).pretty()
19. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which are not belonging to the borough Staten Island or Queens or Bronxor Brooklyn.

 db.restaurent.find({borough:{$nin:['Staten Island','Queens','Bronx','Brooklyn']}},
{_id:0,address:0}).pretty()
20. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which achieved a score which is not more than 10.

 db.restaurent.find({'grades.score':{$lte:10}}).pretty()
21. Write a MongoDB query to find the restaurant Id, name, borough and cuisine for those restaurants
which prepared dish except 'American' and 'Chinees' or restaurant's name begins with letter 'Wil'.

db.restaurent.find({$in:[{cuisine:{$nin:['American','Chinese']}},{name:/^Wil/}]}).pretty()
22. Write a MongoDB query to find the restaurant Id, name, and grades for those restaurants which
achieved a grade of "A" and scored 11 on an ISODate "2014-08-11T00:00:00Z" among many of sur-
vey dates

db.restaurent.find({grades:{$elemMatch:{"date" : ISODate("2014-08-11T00:00:00Z"),"grade" :
"A","score" : 11}}},{restaurant_id:1,name:1,grades:1,_id:0}).pretty()

23. Write a MongoDB query to find the restaurant Id, name and grades for those restaurants where the
2nd element of grades array contains a grade of "A" and score 9 on an ISODate "2014-08-
11T00:00:00Z".

 db.restaurent.find({'grades.1':{$elemMatch:{"date" : ISODate("2014-08-11T00:00:00Z"),"grade" :
"A","score" :9}}},{restaurant_id:1,name:1,grades:1,_id:0}).pretty()

24. Write a MongoDB query to find the restaurant Id, name, address and geographical location for those
restaurants where 2nd element of coord array contains a value which is more than 42 and upto 52

db.restaurent.find({'address.coord.1':{$gt:42, $lte:52}}).pretty().limit(5)
25. Write a MongoDB query to arrange the name of the restaurants in ascending order along with all
the columns.

db.restaurent.find().sort({name:1}).pretty().limit(5)
26. Write a MongoDB query to arrange the name of the restaurants in descending along with all the col-
umns.
 db.restaurent.find({}).sort({name:-1}).pretty().limit(3)

27. Write a MongoDB query to arranged the name of the cuisine in ascending order and for that same
cuisine borough should be in descending order.
 db.restaurent.find({},{_id:0,address:0,grades:0}).sort({cuisine:1, borough:-1}).pretty().limit(5)

28. Write a MongoDB query to know whether all the addresses contains the street or not.

db.restaurent.find({'address.street':{$nin:[null]}}).pretty().limit(5)
29. Write a MongoDB query which will select all documents in the restaurants collection where the co-
ord field value is Double.

db.restaurent.find({'address.coord':{$type:'double'}}).pretty()
30. Write a MongoDB query which will select the restaurant Id, name and grades for those restaurants
which returns 0 as a remainder after dividing the score by 7.

db.restaurent.find({'grades.score':{$mod:[7,0]}},{restaurant_Id:1, name:1, grades:1}).pretty()


31. Write a MongoDB query to find the restaurant name, borough, longitude and attitude and cuisine
for those restaurants which contains 'mon' as three letters somewhere in its name.

 db.restaurent.find({name:/mon/},{name:1,borough:1,coord:1,cuisine:1,_id:0})
32. Write a MongoDB query to find the restaurant name, borough, longitude and latitude and cuisine
for those restaurants which contain 'Mad' as first three letters of its name.

 db.restaurent.find({name:/^Mad/},{name:1,borough:1,coord:1,cuisine:1,_id:0})
Create a Employee Collection add 5 documents: Example:
{empno:111,ename:”Deepali
Vaidya”,sal:40000.00,dept:{deptno12,dname:,”Hr”,dloc:”Mumbai},
Desg:”Analyst”,mgr:{name:”Satish”,num:111},project:[{name:”Project-
1”,Hrs:4},{name:”project- 2”,Hrs:4}]}

db.Employee.insert({empno:111,ename:'Deepali Vaidya',sal:40000.00,dept:
{deptno12,dname:,'Hr',dloc:'Mumbai'}, Desg:'Analyst',mgr:{name:'Satish',num:111},project:
[{name:'Projec1',Hrs:4},{name:'project- 2',Hrs:4}]})

MongoDb Day 2
1. All Employee’s with the desg as ‘CLERK’ are now called as (AO) Administrative Officers. Update
the Employee collection for this.
==> db.Employee.update({Desg:'CLERK'},{$set:{Desg:'Administrative Officres'}})

2. Change the number of hours for project-1 to 5 for all employees with designation analyst.
==> db.Employee.update({Desg:'Analyst'},{$set:{'project.0.Hrs':5}},{multi:true})

3. Add 2 projects project-3 and project-4 for employee whose name starts with ”Deep” with 2 hrs
I am using here ‘Abh’ with project-5,project-6
==> db.Employee.update({ename:/^Abh/},{$push:{project:{$each:[{name:'Project-5',Hrs:2},
{name:'Project-6',Hrs:2}]}}},{multi:true})
4. Add bonus rs 2000 for all employees with salary > 50000
==> db.Employee.update({sal:{$gt:50000}},{$inc:{bonus:2000}},{multi:true})
5. Add bonus rs 1500 if salary <50000 and > 30000
==>db.Employee.update({sal:{$gte:30000,$lte:50000}},{$inc:{bonus:1500}},{multi:true})
6. increment bounus by 1000 for all employees if salary <=30000
==> db.Employee.update({sal:{$lte:30000}},{$inc:{bonus:1000}},{multi:true})

7. Change manager name to Tushar for all employees whose manager is currently “satish” And
manager number to 3333

==> b.Employee.update({'mgr.name':'Satish'},{$set:{'mgr.name':'Tushar','mgr.num':3333}},
{multi:true})

8. Increase salary of all employees from “purchase department” by 15000


==> db.Employee.update({'dept.dname':'Purchase'},{$inc:{sal:15000}},{multi:true})

9. Decrease number of hrs by 2 for all employees who are working on project-2
==>

db.Employee.update({project:{$elemMatch:{name:'Project-2'}}},{$inc:{'project.1.Hrs':-2}},
{multi:true})
db.Employee.update({'project.name':'project-2'},{$inc:{'project.3.Hrs':-2}},{multi:true})

10. Delete project-2 from all employee document if they are working on the project for 4 hrs.
==> db.Employee.update({project:{$elemMatch:{name:'Project-2',Hrs:4}}},{$unset:{project:
{$elemMatch:{name:'',Hrs:''}}}},{multi:true})

acknowledged: true,

insertedId: null,

matchedCount: 0,

modifiedCount: 0,

upsertedCount: 0

11. Change the salary of employees to 10000 only if their salary is < 10000
==>db.Employee.update({sal:{$gt:10000}},{$set:{sal:10000}},{multi:true})
12. Increase bonus of all employees by 500 if the bonus is <2000 or their salary is <
20000 or if employee belong to sales department

==>

db.Employee.update({$or:[{sal:{$gt:20000},bonus:{$lt:2000}}],dname:'Sales'},{$inc:
{bonus:500}},{multi:true})

13. Add 2 new project at position 2 for all employees with designation analyst or salary is equal to
either 30000 or 33000 or 35000
==> db.Employee.update({$or:[{Desg:'Analyst'},sal:{$in:[30000,33000,35000]}]},{$set:{'project.1':
{name:'Project-11',Hrs:2},'project.2':{name:'Project-22',Hrs:2}}},{multi:true})
14. Delete last project of all employees with department name is “HR” and if the location is Mumbai
==>db.Employee.update({'dept.dname':'Hr','dept.dloc':'Mumbai'},{$pop:{project:1}},{multi:true})

15. Change designation of all employees to senior programmer if they are working on
name:”Project-1” for 4 hrs
==>db.Employee.update({project:{$elemMatch:{name:'Project-1',Hrs:4}}},{$set:{Desg:'Senior
Programmer'}},{multi:true})

16. Add list of hobbies in all employees document whose manager is Rajan or Revati
==>db.Employee.update({'mgr.name':{$in:['Madhu','Suyash']}},{$set:{hobbies:['Swimming','Playing
Cricket']}},{multi:true})
17. Add list of skillset in all employee documents who are working on project-4 for 3 hrs or on
project-3 for 4 hrs
==>db.Employee.update({$or:[{project:{$elemMatch:{name:'Project-4',Hrs:4}}},{project:
{$elemMatch:{name:'Project-3',Hrs:4}}}]},{$set:{Skillset:['Java','.NET']}},{multi:true})
18. Add a new hobby as blogging at 3 position in hobbies array for all employess whose name starts
with R or p and ends with j or s
==> db.Employee.update({ename:/^[OS].*[el]$/},{$push:{Skillset:'Blogging'}},{multi:true})
19. Increase salary by 10000 for all employees who are working on project-2 or project-3 or project-
1
==> db.Employee.find({$or:[{project:{$elemMatch:{name:'Project-1'}}},{project:{$elemMatch:
{name:'Project-2'}}},{project:{$elemMatch:{name:'Project-3'}}}]},{$inc:{sal:10000}},{multi:true})

Decrease bonus by 1000 rs And increase salary by 1000rs for all employees whose department
location is Mumbai
==>db.Employee.find({'dept.dname':'Mumbai'},{$inc:{sal:1000},{$inc:{bonus:-1000}}},
{multi:true})

20. Remove all employees working on project-1


21. Replace document of employee with name “Deepak to some new document
22. Change skill python to python 3.8 for all employees if python is there in the skillset

==> db.Employee.update({Skillset:'Python'},{$push:{Skillset:'Python 3.8'}},{multi:true})

23. Add 2 skills MongoDb and Perl at the end of skillset array for all employees who are working at
Pune location
==> db.Employee.update({'dept.dloc':'Pune'},{$push:{Skillset:['MongoDb','Perl']}},{multi:true})

24. Delete first hobby from hobby array for all employees who are working on project-1 or project-2
==> db.Employee.update({$or:[{project:{$elemMatch:{name:'Project-1'}}},{project:{$elemMatch:
{name:'Project-2'}}}]},{$pop:{hobbies:-1}},{multi:true})

25. Delete last hobby from hobbies array for all employees who are working on project which is at 2
nd position in projects array for 4 hrs
==>db.Employee.update({project:{$elemMatch:{Hrs:4}}},{$pop:{hobbies:1}},{multi:true})
26. Add 2 new projects at the end of array for all employees whose skillset contains Perl or python
==>db.Employee.update({Skillset:{$in:['Python','Perl']}},{$push:{project:
{name:'Project_new2',Hrs:10}}},{multi:true})

db.Employee.update({Skillset:{$in:['Python','Perl']}},{$push:{project:{name:'Project_new1',Hrs:10}}},
{multi:true})

27. Change hrs to 6 for project-1 for all employees if they working on the project-1 for < 6 hrs.
otherwise keep the existing value.
==>

Notes:

To delete key of arrays of object at specific location


db.Employee.update({bonus:8000,empno:213},{$unset:{'project.3.Hts':''}})

TO remove array elements at specific position


db.Employee.update({empno:{$in:[213,214]}},{$unset:{'Skillset.2':''}},{multi:true})

You might also like