INDEX
Sr.No Title Date Sign
1. MongoDB Basics 09-07-18
2. Simple Queries with MongoDB 14-07-18
3. Implementing Aggregation 17-07-18
4. Java and MongoDB 21-07-18
5. PHP and MongoDB 24-07-18
6. Python and MongoDB 28-07-18
7. Programs on basic jQuery 03-08-18
8. jQuery Advanced 07-08-18
9. JSON 14-08-18
10. Create a JSON file and import it to MongoDB 20-08-18
PRACTICAL NO :- 1
➢MONGO DB BASICS
a. Write a MongoDB query to create and drop database.
Syntax:-
use DATABASE_NAME
Query:-
>use college
Syntax:-
db.dropDatabase()
Query:-
> db.dropDatabase()
b. Write a MongoDB query to create, display and drop
collection
Syntax:-
db.createCollection(name, options)
Query:-
>db.createCollection(“student”)
Syntax:-
show collections
Query:-
>show collections
Syntax:-
db.COLLECTION_NAME.drop()
Query:-
>db.student.drop()
c. Write a MongoDB query to insert, query, update and delete
a document.
INSERT DOCUMENT
Syntax:-
db.COLLECTION_NAME.insert(document)
Query:-
>db.mycol.insert({course:"BSC_IT",duration:"3",
url:"ldsonawane.com"})
QUERY DOCUMENT
Syntax:-
>db.COLLECTION_NAME.find()
Query:-
>db.mycol.find()
UPDATE DOCUMENT
Syntax:-
>db.COLLECTION_NAME.update(SELECTION_CRITERIA,
UPDATED_DATA)
Query:-
>db.mycol.update({"course":"BSC_IT"},{$set:{"durration":4}})
DELETE DOCUMENT
Syntax:-
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Query:-
>db.mycol.remove({"course":"BCOM"})
PRACTICAL NO:-2
➢SIMPLE MONGODB QUERIES
• Write a mongo DB query to display all the
documents in the collection restaurants:
Query:-
db.restaurants.find()
• Write a MongoDB query to display the fields
restaurant_id, name, borough and cuisine for all the
documents in the collection restaurant.
Query:-
db.restaurants.find({},{"restaurant_id" :
1,"name":1,"borough":1,"cuisine" :1});
• Write a MongoDB query to display the first 5
restaurant which is in the borough Bronx
Query:-
db.restaurants.find({"borough": "Bronx"}).limit(5);
• Write a MongoDB query to find the restaurants that
achieved a score is more than 80 but less than 100
Query:-
db.restaurants.find({grades : {
$elemMatch:{"score":{$gt : 80 , $lt :100}}}});
• 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
survey dates.
Query:-
db.restaurants.find({"grades.date":ISODate("2014-
08-11T00:00:00Z"),"grades.grade":"A","grades.score"
:11},{"restaurant_id":1,"name":1,"grades":1});
PRACTICAL NO:-3
➢Implementing Aggregation
a. Write a MongoDB query to use sum, avg, min and max
expression.
SUM
Syntax:-
>db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION)
Query:-
db.fees.aggregate({$group:{_id:"name",total:{$sum:"$amou
nt"}}})
AVG
Syntax:-
>db.COLLECTION_NAME.aggregate([{$group : {_id : "$by_user",
num_tutorial : {$avg : "$likes"}}}])
Query:-
db.fees.aggregate({$group:{_id:"name",total_avg:{$avg:"$a
mount"}}})
MIN
Syntax:-
>db.COLLECTION_NAME.aggregate[{$group : {_id : "$by_user",
num_tutorial : {$min : "$likes"}}}])
Query:-
db.fees.aggregate({$group:{_id:"name",minimum:{$min:"$a
mount"}}})
MAX
Syntax:-
>db.COLLECTION_NAME.aggregate[{$group : {_id : "$by_user",
num_tutorial : {$max : "$likes"}}}])
Query:-
db.fees.aggregate({$group:{_id:"name",maximum:{$max:"$a
mount"}}})
b. Write a MongoDB query to use push and addToSet
expression.
PUSH
Syntax:-
>db.COLLECTION_NAME.update({ $push: { <field1>: <value1>, ... } })
Query:-
db.students.update({ name: “sid” },{ $push: { marks: 89 } })
ADDTOSET
Syntax:-
>db.COLLECTION_NAME.update({ <field> : <value> } , { $addtoset:
{ <field1>: <addition> } })
Query:-
db.students.update({ name: “sid” },{ $addToSet: {
marks:{$each:[89,70,69]} } })
c. Write a MongoDB query to use first and last expression
FIRST
Syntax:-
>db.COLLECTION_NAME.aggregate([$group : {_id: “$by_user”, first u
rl : {$first : “$url”} } })
Query:-
db.fees.aggregate({$group:{_id:"name",total:{$first:"$name"}}}
)
LAST
Syntax:-
>db.COLLECTION_NAME.aggregate([$group : {_id: “$by_user”, last ur
l : {$last : “$url”} } })
Query:-
db.fees.aggregate({$group:{_id:"name",total:{$last:"$name"}}})
PRACTICAL NO :- 4
➢JAVA AND MONGODB
a. Connecting Java with MongoDB and inserting, retrieving,
updating and deleting
INSERT
Query:-
public class Mongodb_connection_insert
{
public static void main(String args[])
{
try{
MongoClient mongoclient =
new MongoClient("localhost",27017);
DB db=mongoClient.getDB("testdb");
System.out.println("Connection successful");
DBCollection collec=db.getCollection("stucollec");
BasicDBObject doc= new
BasicDBObject("student","testdb").append("name","Arun
").apped("class","v").append("roll_no",5);
collec.insert(doc);
System.out.println("inserted");}
catch(Exception e)
{
System.err.println(e.getClass().getName()+"."+e.get
Message())
}
}
}
RETRIVE
Query:-
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.WriteConcern;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.DBCursor;
import com.mongodb.ServerAddress;
import java.util.Arrays;
public class Mongodb_connection_find_all_documents
{
public static void main(String args[])
{
try{
MongoClient mongoclient=new
MongoClient("localhost",27017);
DB db=mongoClient.getDB("testdb");
DBCollection collec=db.getCollection("stucollec");
DBCursor cursor=collec.find();
try
{
While(cursor.hasNext())
{
System.out.println(cursor.next());
}
} finally
{
cursor.close();
}
} catch(Exception e)
{
System.err.println(e.getClass().getName()+"."+e.getMessage());
}
}
}
UPDATE
Query:-
public class Mongodb_connection_update_document
{
public static void main(String args[])
{
try{
MongoClient mongoclient =new
MongoClient("localhost",27017);
DB db=mongoClient.getDB("testdb");
DBCollection collec=db.getCollection("stucollec");
DBObject query=new BasicDBObject(“name”,”sabina”);
DBObject update=new BasicDBObject();
Update.put(“$set”,new BasicDBObject(“roll_no”,13));
WriteResult result=collec.update(query,update);
DBCursor cursor=collec.find();
try{
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
}
finally
{ cursor close();
}
}
catch(Exception e)
{
System.err.println(e.getClass().getName()+"."+e.getMessage());
}
}
}
DELETE
Query:-
public class Mongodb_connection_delete_document
{
public static void main(String args[])
{
try{
MongoClient mongoclient =new
MongoClient("localhost",27017);
DB db=mongoClient.getDB("testdb");
DBCollection collec=db.getCollection("stucollec");
DBObject query=new BasicDBObject(“name”,”sabina”);
DBObject update=new BasicDBObject();
Update.put(“$set”,new BasicDBObject(“roll_no”,13));
WriteResult result=collec.remove(query);
DBCursor cursor=collec.find();
try{
while(cursor.hasNext())
{
System.out.println(cursor.next());
}
}
finally
{ cursor close();
}
}
catch(Exception e)
{
System.err.println(e.getClass().getName()+"."+e.getMessage());
}
}
}
PRACTICAL NO :- 5
➢PHP AND MONGODB
a. Connecting PHP with MongoDB and inserting, retrieving,
updating and deleting.
CONNECTION
Query:-
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
?>
INSERTING
Query:-
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
$document = array(
"title" => "MongoDB",
"description" => "database",
"likes" => 100,
"url" => "http://www.tutorialspoint.com/mongodb/",
"by" => "tutorials point"
);
$collection->insert($document);
echo "Document inserted successfully";
?>
RETRIEVING
Query:-
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
$cursor = $collection->find();
// iterate cursor to display title of documents
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
UPDATE
Query:-
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
// now update the document
$collection->update(array("title"=>"MongoDB"),
array('$set'=>array("title"=>"MongoDB Tutorial")));
echo "Document updated successfully";
// now display the updated document
$cursor = $collection->find();
// iterate cursor to display title of documents
echo "Updated document";
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
DELETE
Query:-
<?php
// connect to mongodb
$m = new MongoClient();
echo "Connection to database successfully";
// select a database
$db = $m->mydb;
echo "Database mydb selected";
$collection = $db->mycol;
echo "Collection selected succsessfully";
// now remove the document
$collection->remove(array("title"=>"MongoDB Tutorial"),false);
echo "Documents deleted successfully";
// now display the available documents
$cursor = $collection->find();
// iterate cursor to display title of documents
echo "Updated document";
foreach ($cursor as $document) {
echo $document["title"] . "\n";
}
?>
PRACTICAL NO :- 6
➢PYTHON AND MONGODB
a) Connecting Python with MongoDB and inserting, retrieving,
updating and deleting.
python -m pip install pymongo
INSERT
Query:-
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.testdb
student1={“name”:”Eugene”,”classid”:’V’,”rollno”:1}
students=db.students
students_id=students.insert(student1)
RETRIEVE
Query:-
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.testdb
students=db.students
for stud in students.find({“rollno”:{“gte”:2}}):
print(stud)
UPDATE
Query:-
import pymongo
myclient =
pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["customers"]
myquery = { "address": "Valley 345" }
newvalues = { "$set": { "address": "Canyon 123" } }
mycol.update_one(myquery, newvalues)
#print "customers" after the update:
for x in mycol.find():
print(x)
DELETE
Query:-
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.testdb
students=db.students
students.remove({‘rollno’:3})
print(student)
PRACTICAL NO :- 7
➢PROGRAMS ON BASIC JQUERY
a) jQuery Basic, jQuery Events
click()
<!DOCTYPE html>
<html>
<head>
<script src="file:///C:/js/jquery-3.3.1.min.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>
mousedown()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});
});
</script>
</head>
<body>
<p id="p1">This is a paragraph.</p>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
focus()
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
});
</script>
</head>
<body>
Name: <input type="text" name="fullname"><br>
Email: <input type="text" name="email">
</body>
</html>
blur()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});
});
</script>
</head>
<body>
Name: <input type="text" name="fullname"><br>
Email: <input type="text" name="email">
</body>
</html>
b) jQuery Selectors, jQuery Hide and Show effects
selectors()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me to hide paragraphs</button>
</body>
</html>
Hide() and show()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("#hide").click(function(){
$("p").hide();
});
$("#show").click(function(){
$("p").show();
});
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>
toggle()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").toggle();
});
});
</script>
</head>
<body>
<button>Toggle between hiding and showing the
paragraphs</button>
<p>This is a paragraph with little content.</p>
<p>This is another small paragraph.</p>
</body>
</html>
c) jQuery fading effects, jQuery Sliding effects
fadeIn()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeIn();
$("#div2").fadeIn("slow");
$("#div3").fadeIn(3000);
});
});
</script>
</head>
<body>
<p>Demonstrate fadeIn() with different parameters.</p>
<button>Click to fade in boxes</button><br><br>
<div id="div1"
style="width:80px;height:80px;display:none;background-
color:red;"></div><br>
<div id="div2"
style="width:80px;height:80px;display:none;background-
color:green;"></div><br>
<div id="div3"
style="width:80px;height:80px;display:none;background-
color:blue;"></div>
</body>
</html>
fadeToggle()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeToggle();
$("#div2").fadeToggle("slow");
$("#div3").fadeToggle(3000);
});
});
</script>
</head>
<body>
<p>Demonstrate fadeToggle() with different speed
parameters.</p>
<button>Click to fade in/out 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>
slideDown()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideDown("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
display: none;
}
</style>
</head>
<body>
<div id="flip">Click to slide down panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
slideUp()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("#flip").click(function(){
$("#panel").slideUp("slow");
});
});
</script>
<style>
#panel, #flip {
padding: 5px;
text-align: center;
background-color: #e5eecc;
border: solid 1px #c3c3c3;
}
#panel {
padding: 50px;
}
</style>
</head>
<body>
<div id="flip">Click to slide up panel</div>
<div id="panel">Hello world!</div>
</body>
</html>
PRACTICAL NO :- 8
jQuery Advanced
a) jQuery Animation effects, jQuery Chaining
ANIMATION
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.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:absol
ute;"></div>
</body>
</html>
jQuery animate() - Manipulate Multiple
Properties
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").animate({
left: '250px',
opacity: '0.5',
height: '150px',
width: '150px'
});
});
});
</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:absol
ute;"></div>
</body>
</html>
jQuery Method Chaining
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);
});
});
</script>
</head>
<body>
<p id="p1">jQuery is fun!!</p>
<button>Click me</button>
</body>
</html>
b) jQuery Callback, jQuery Get and Set
Contents
jQuery Callback Functions
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
});
</script>
</head>
<body>
<button>Hide</button>
<p>This is a paragraph with little content.</p>
</body>
</html>
Get Content - text()
<!DOCTYPE html>
<html>
<head>
<script src=" file:///C:/js/jquery-3.3.1.min.js "></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
alert("Text: " + $("#test").text());
});
$("#btn2").click(function(){
alert("HTML: " + $("#test").html());
});
});
</script>
</head>
<body>
<p id="test">This is some <b>bold</b> text in a paragraph.</p>
<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>
</body>
</html>
PRACTICAL NO:-9
➢JSON
a) creating JSON
• JSON stands for JavaScript Object Notation
• JSON is a lightweight data interchange format
• JSON is language independent *
• JSON is "self-describing" and easy to understand
Example:-
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
b)Parsing JSON
file:-
<!DOCTYPE html>
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a
file.</h2>
<p>The content is written in JSON format, and can easily
be converted into a JavaScript object.</p>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML =
myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
<p>Take a look at <a href="json_demo.txt"
target="_blank">json_demo.txt</a></p>
</body>
</html>
example:-
var obj = JSON.parse(text);
PRACTICAL NO:-10
➢ Create a JSON file and import it to
MongoDB
Import MongoDB to JSON:-
mongoimport --db dbName --collection collectionName --file
fileName.json --jsonArray
Export MongoDB to JSON:-
mongoexport --db sales --collection contacts --out contacts.js
on