0% found this document useful (0 votes)
41 views29 pages

Mongo DB Pracs 1to 3-1

Uploaded by

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

Mongo DB Pracs 1to 3-1

Uploaded by

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

PRACTICAL 1

MongoDB Basics
a Write a MongoDB query to create and drop database.
b Write a MongoDB query to create, display and drop collection
c Write a MongoDB query to insert , update and delete a document

Solution

Type in command prompt


mongosh
you get test>
1) Write a MongoDB query to create database.
use office

2) To create collection
db.createCollection(“emp”)
3) To insert data in collection emp
db.emp.insert({emp_id:1,emp_name:"SAMEER",age:22,salary:20000})

Similary using page up insert more data


db.emp.insert({emp_id:2,emp_name:"KAMAL",age:23,salary:25000})
db.emp.insert({emp_id:3,emp_name:"KIRAN",age:25,salary:22000})
db.emp.insert({emp_id:4,emp_name:"MARIA",age:27,salary:30000})
4) To display data
db.emp.find()

5) To drop collection
db.dropDatabase();
To see if data deleted or not
db.emp.find()
using page up again insert 4 data for further queries

6) To update employee id 2 salary to 40000


db.emp.update({emp_id:2},{$set:{salary:40000}})

To view the updated data


db.emp.find()

7) To delete/remove record 4
db.emp.remove({emp_id:4})

db.emp.find()
Practical 2
Simple Queries with MongoDB

1) Create database Employee


use Employee
2) Create collection ee
db.createCollection("ee")
3) Insert emp_id, name, city, dept,age
db.ee.insert({emp_id:1,name:"vina",city:"mumbai",dept:"IT",age:25});
db.ee.insert({emp_id:2,name:"PRITAM",city:"THANE",dept:"CS",age:24});
db.ee.insert({emp_id:3,name:"AMAN",city:"THANE",dept:"IT",age:22});
4) Display output in pretty format
db.ee.find().pretty()
output
Employee> db.ee.find().pretty()
[
{
_id: ObjectId('667808dda74d65d42290defe'),
emp_id: 1,
name: 'vina',
city: 'mumbai',
dept: 'IT',
age: 25
},
{
_id: ObjectId('6678090fa74d65d42290deff'),
emp_id: 2,
name: 'PRITAM',
city: 'THANE',
dept: 'CS',
age: 24
},
{
_id: ObjectId('66780937a74d65d42290df00'),
emp_id: 3,
name: 'AMAN',
city: 'THANE',
dept: 'IT',
age: 22
}
]
5) Display document with following condition : department IT , age greater than 22
(display only name ,city and dept of that document .
Note : to display any field we write 1, if we don’t want to display write 0 . here we
don’t want to display _id so written
Use and function when we have more than 1 condition

db.ee.find({$and:[{dept:"IT"},{age:{$gt:22}}]},{name:1,city:1,dept:1,_id:0});
output
[ { name: 'vina', city: 'mumbai', dept: 'IT' } ]
6) Display the name of employee who stays in THANE and age is less than 23
db.ee.find({$and:[{city:"THANE"},{age:{$lt:23}}]},{name:1});
output
[ { _id: ObjectId('66780937a74d65d42290df00'), name: 'AMAN' } ]
Donot diplay _id
db.ee.find({$and:[{city:"THANE"},{age:{$lt:23}}]},{name:1,_id:0});
output
[ { name: 'AMAN' } ]
7) Display name and department of employe who are in IT department
db.ee.find({dept:"IT"},{name:1,dept:1,_id:0})
[ { name: 'vina', dept: 'IT' }, { name: 'AMAN', dept: 'IT' } ]
Practical 3
Implementing Aggregation
a Write a MongoDB query to use sum, avg, min and max expression.
b Write a MongoDB query to use push and addToSet expression.
c Write a MongoDB query to use first and last expression.
Aggregation is a process of selecting data from a collection . it process multiple documents
and gives computed result like sum , average , min , max
1) Create database college
use college
2) Create collection student
db.createCollection("student")
3) Insert 4 to 6 documents in it . with some same city
db.student.insert({stud_id:1,name:"ajay",age:20,department:"it",city:"mumbai",salar
y:20000})
db.student.insert({stud_id:2,name:"bijay",age:22,department:"cs",city:"thane",salary:
30000})
db.student.insert({stud_id:3,name:"cindrella",age:24,department:"it",city:"mumbai",s
alary:20000})
db.student.insert({stud_id:4,name:"cindrella",age:24,department:"it",city:"thane",sal
ary:40000})
4) Display maximum age of student in each city
(use aggregate function group by id city and display age where age is maximum)
db.student.aggregate([{$group:{_id:"$city",age:{$max:"$age"}}}])
output
[ { _id: 'mumbai', age: 24 }, { _id: 'thane', age: 24 } ]
5) Display minimum age of student in each city

db.student.aggregate([{$group:{_id:"$city",age:{$min:"$age"}}}])
[ { _id: 'mumbai', age: 20 }, { _id: 'thane', age: 22 } ]
6) Display average age of student in each city

db.student.aggregate([{$group:{_id:"$city",age:{$avg:"$age"}}}])
7) Display sum age of student in each city

db.student.aggregate([{$group:{_id:"$city",age:{$sum:"$age"}}}])
[ { _id: 'mumbai', age: 44 }, { _id: 'thane', age: 46 } ]

8) Write a MongoDB query to use push operator


$push
The $push operator appends a specified value to an array.

use prac4
db.createCollection("order");
db.order.insertMany([
... {
... "customerId": 1023,
... "orderTimestamp": NumberLong("1646460073000"),
... "shippingDestination": "336, Street No.1 Pawai Mumbai",
... "purchaseOrder": 1000,
... "contactNumber":"9898987676",
... "items": [
... {
... "itemName": "BERGER",
... "quantity": 1,
... "price": 500
... },
... {
... "itemName": "VEG PIZZA",
... "quantity": 1,
... "price": 800
... }
... ]
... },
... {
... "customerId": 1027,
... "orderTimestamp": NumberLong("1646460087000"),
... "shippingDestination": "445, Street No.2 Pawai Mumbai",
... "purchaseOrder": 2000,
... "contactNumber":"9898987676",
... "items": [
... {
... "itemName": "BERGER",
... "quantity": 1,
... "price": 500
... },
... {
... "itemName": "NON-VEG PIZZA",
... "quantity": 1,
... "price": 1200
... }
... ]
... }
... ]);

db.order.find()
db.order.updateOne( { "customerId": 1023 }, { $push: { "items":{ "itemName": "PIZZA
MANIA", "quantity": 1, "price": 800 } } });
db.order.find()

The mongo shell query of the $addToSet operator is similar to the $push operator, but
the $addToSet doesn’t insert the duplicate value in the array.
db.order.updateOne( { "customerId": 1023 }, { $addToSet: { "items":{ "itemName":
"PASTA", "quantity": 1, "price": 1000 } } });

example 2
1) use office
2) db.createCollection("mycollection")

3)
db.mycollection.insert([
{
title: 'MongoDB Overview',
description: 'MongoDB is no sql database',
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 100
},
{
title: 'NoSQL Database',
description: "NoSQL database doesn't have tables",
by: 'tutorials point',
url: 'http://www.tutorialspoint.com',
tags: ['mongodb', 'database', 'NoSQL'],
likes: 20,
comments: [
{
user:'user1',
message: 'My first comment',
dateCreated: new Date(2013,11,10,2,35),
like: 0
}
]
}
])

4)
db.mycollection.find()
5)
db.mycollection.aggregate([{$group : {_id : "$by", num_tutorial : {$sum : "$likes"}}}])
output
[ { _id: 'tutorials point', num_tutorial: 120 } ]
db.mycollection.aggregate([{$group : {_id : "$title", num_tutorial : {$sum : "$likes"}}}])

output
[
{ _id: 'NoSQL Database', num_tutorial: 20 },
{ _id: 'MongoDB Overview', num_tutorial: 100 }
]

Similarly try other min ,average , max

$push (aggregation) (NOTE HERE NOT ADDING BUT RETRIEVING DATA)


Definition

$push returns an array of all values that result from applying an expression to
documents.

db.mycollection.aggregate([{$group : {_id : "$by", URL : {$push: "$url"}}}])

OUTPUT : Group by id : by and display all url with caption URL


[
{
_id: 'tutorials point',
URL: [
'http://www.tutorialspoint.com',
'http://www.tutorialspoint.com'
]
}
]

Similarly try
db.mycollection.aggregate([{$group : {_id : "$likes", AUTHOR : {$push: "$by"}}}])
output :( group by likes and display all by with caption AUTHOR )
[
{ _id: 100, AUTHOR: [ 'tutorials point' ] },
{ _id: 20, AUTHOR: [ 'tutorials point' ] }
]
c)Write a MongoDB query to use first and last expression.
(i)First : shows first occurance

db.mycollection.aggregate([{$group:{_id:"$by",FIRST_URL:{$first:"$url"}}}])
output : group by by and display first url
[
{
_id: 'tutorials point',
FIRST_URL: 'http://www.tutorialspoint.com'
}
]
Similarly try
db.mycollection.aggregate([{$group:{_id:"$by",TOTAL_LIKES:{$first:"$likes"}}}])
output
[ { _id: 'tutorials point', TOTAL_LIKES: 100 } ]

Similarly try last

db.mycollection.aggregate([{$group:{_id:"$by",TOTAL_LIKES:{$last:"$likes"}}}])
output
{ _id: 'tutorials point', TOTAL_LIKES: 20 } ]
office>
EXTRA FOR PRACTICE NOT IN PRACTICAL SYLLABUS
1) Create database office
Use office
2) Show all database
Show dbs
3) In office create collection student
db.createCollection('student')
4) insert document using insertOne
db.student.insertOne({name:"kamal",age:19})
db.student.find()
5) insert document using insertMany
db.student.insertMany([{name:"pritam",country:"india"},{name:"rahul",age:20}])
db.student.find()
6) to display limited result
db.student.find().limit(10)

7) Find student by name smith

db.student.find({"name": "Smith"}).count()
8) All age that do NOT have exactly 20
> db.student.find({age: {$ne: 20}})
9) order by age, in ascending order (smallest values first)
> db.student.find().sort({age: 1})
10) order by age, in ascending order (largest values first)
> db.student.find().sort({age:-1})

Practical 5 jQuery Effects - Hide


• jQuery is a lightweight, "write less, do more", JavaScript library.
• The purpose of jQuery is to make it much easier to use JavaScript on your website.
• jQuery takes a lot of common tasks that require many lines of JavaScript code to
accomplish, and wraps them into methods that you can call with a single line of code.
The jQuery library contains the following features:
• HTML/DOM manipulation
• CSS manipulation
• HTML event methods
• Effects and animations
• AJAX
• Utilities
Save above file as jquery1.html
Steps
1) You require jquery file . save it as jquery.js (neary 440 pages code)
2) Create below html file with link to jquery.js. both files should be in same location
3) See output in web browser

<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>

<p>If you click on me, I will disappear.</p>


<p>Click me away!</p>
<p>Click me too!</p>

</body>
</html>

Output

5B Jquery : Animation
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({left: '250px'});
});
});
</script>
</head>
<body>

<button>Start Animation</button>

<p>By default, all HTML elements have a static position, and cannot be moved. To
manipulate the position, remember to first set the CSS position property of the element to
relative, fixed, or absolute!</p>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

</body>
</html>
PRACTICAL 6
6A Practical fade boxes
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeTo("slow", 0.15);
$("#div2").fadeTo("slow", 0.4);
$("#div3").fadeTo("slow", 0.7);
});
});
</script>
</head>
<body>

<p>Demonstrate fadeTo() with different parameters.</p>

<button>Click to fade boxes</button><br><br>


<div id="div1" style="width:80px;height:80px;background-color:red;"></div><br>
<div id="div2" style="width:80px;height:80px;background-color:green;"></div><br>
<div id="div3" style="width:80px;height:80px;background-color:blue;"></div>

</body>
</html>

PRACTICAL 7
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$("th").addClass("menu_title");
$("td").addClass("submenu_title");
});
</script>
<style>
.menu_title{
background-color:black;
color:white;
font-size:30px;
}
.submenu_title{
background-color:Cyan;
color:Black;
font-size:20px;
}
.title{
color:#ad1625;
font-size:50px;
text-align:center;
}
</style>
<body>
</head>
<body>
<p> WELCOME TO MY KITCHEN </p>
<h1 class = "tittle"><center>CHINESE CORNER</h1>
<table align="center" width="40%">
<tr><th colspan=2>Indian</th></tr>
<tr><td>Biryani</td>
<td>250/-</td>
</tr>
<tr><td>Kol. Biryani</td>
<td>390/-</td>
</tr>
<tr>
<th colspan="2">Chinese</th>
</tr>
<tr>
<td> Manchau Noodles</td>
<td>350/-</td>
</tr>
<tr>
<td>Triple Fried Rice</td>
<td>370/-</td>
</tr>
<tr>
<th colspan="2">Continential</th>
</tr>
<tr>
<td> Crispy Calamari Rings.</td>
<td>300/-</td>
</tr>
<tr>
<td>Chicken And Cheese Salad.</td>
<td>470/-</td>
</tr>
<tr>
</body>
</html>
PRACTICAL 7B
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
img{
position: relative;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$("img").animate({left:'+=550px'},4000);
});
$(".stop").click(function(){
$("img").stop();
});
});
</script>
</head>
<body>
<p> HI EVERYONE </p>
<button>Start Animation</button>
<button type="button" class="stop">Stop Animation</button>
<div>
<p>
<img src="CAKE.png"
width=209 height="239"/>
</p>
</div>
</body>
</html>

PRACTICAL 8

JSON

· JSON stands for JavaScript Object Notation


· JSON is a lightweight format for storing and transporting data

· JSON is often used when data is sent from a server to a web page

· JSON is "self-describing" and easy to understand

This example defines an employees object: an array of 3 employee records (objects):

{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}

JSON Data - A Name and a Value

JSON data is written as name/value pairs, just like JavaScript object properties.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed
by a value:

"firstName":"John"

To see output install node.js

1. Download node js for window

2. Prebuilt installer -> download


Practical 8A : Converting JavaScript object to JSON . Creating JSON

Create following JavaScript file in notepad

Save as aa.js

let student={

name:"heena",

age:47,

};

let ans=JSON.stringify(student);

console.log(ans)

Output

C:\Users\mubar\Desktop>node aa.js

{"name":"heena","age":47}

8B Parsing
· A common use of JSON is to exchange data to/from a web server.

· When receiving data from a web server, the data is always a string.

· Parse the data with JSON.parse(), and the data becomes a JavaScript
object.

let str='{"name":"sahil","age":19}';

let ob=JSON.parse(str);

console.log(ob);

see output

C:\Users\mubar\Desktop>node parse.js

{ name: 'sahil', age: 19 }

Practical 8C : Export Mongodb to JSON

Open MongoDB Compass

Select any database and collection

Click export button

Select convert to JSON -> Select the location to save -> see the file is created
To see output :

Right click the file created and open with notepad


PRACTICAL 9 :

9A How to create replica

What is Replication in MongoDB?


Data replication ensures data security not only in the case of a single server failure but also in
the case of a hardware failure. Replication stores multiple data copies across various data
servers, allowing users to recover data whenever required.

MongoDB supports replication with the help of Replica Sets. These Mongodb Replica Sets
are a combination of various mongod instances, each of them having a single primary node
and multiple secondary nodes.

9B : How to create backup of database

Dump MongoDB Data

To create backup of database in MongoDB, you should use mongodump command. This
command will dump the entire data of your server into the dump directory. There are many
options available by which you can limit the amount of data or create backup of your remote
server.

The basic syntax of mongodump command is as follows

>mongodump
9C how to restore database from the backup

Restore data

To restore backup data MongoDB's mongorestore command is used. This command restores
all of the data from the backup directory.

Syntax

The basic syntax of mongorestore command is

>mongorestore

● $ mongod --port 27017 --dbpath /var/lib/mongodb --replSet replicaSet1


● MongoDB uses the port 27017 as its default port. In case the user doesn’t specify the
port number, MongoDB automatically establishes a connection with the default port.
● The –repelset parameter specifies the name of the Replica Set, which will store
various MongoDB instances. Here the replica set is called replicaSet1

You might also like