0% found this document useful (0 votes)
177 views

NGT Practical

This document provides code examples for performing various operations in MongoDB such as creating databases and collections, inserting documents, querying, updating and deleting documents. It also includes examples of aggregation queries using expressions like sum, avg, min, max, push and addToSet. The document discusses setting up a MongoDB replica set, importing data from JSON files, and connecting to a MongoDB database from a Java program.

Uploaded by

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

NGT Practical

This document provides code examples for performing various operations in MongoDB such as creating databases and collections, inserting documents, querying, updating and deleting documents. It also includes examples of aggregation queries using expressions like sum, avg, min, max, push and addToSet. The document discusses setting up a MongoDB replica set, importing data from JSON files, and connecting to a MongoDB database from a Java program.

Uploaded by

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

PRACTICAL 1

A.Write a MongoDB query to create and drop database

Creating database

Drop Database

B.Write a MongoDB query to create, display and drop collection

db.createCollection("diz",{capped:true,autoIndexId:true,size:641232,max:200})

Display Collection

show collections
Drop Collection

db.aditya.drop()

C.Write a MongoDB query to insert, query, update and delete a document.

COMMAND:

db.student.insert({"name":"aditya","rollno":4})

for(var i=1;i<=20;i++) db.student.insert({"name":"test user"+i,"age":4+i})

db.aditya.insertOne({"name":"aditya","rollno":34,"age":19})
db.aditya.insertMany([{"name":"aditya","rollno":34,"age":19},{"name":"aditya34","roll
no":74,"age":9}])

1.Create a database by the name college


2. Create a collection student with the following data: student id ,student name,student
address( nerul,seawoods,panvel), phone no and age(21-30).
3. Insert 15 documents
4.Display only the first document from the collection
5. Dis[play the name of student staying in seawoods
6. Display the display staying in nerul and age greater than 23
7. Display the details of students either in nerul or panvel and age less than 26.
8.Update the city from nerul to kharghar for all students staying in nerul
9.Add a new field hobby for all the student collection data

1)

PRACTICAL 2
Simple Queries with MongoDB
MONGOIMPORT COMMAND
mongoimport --host localhost --db aditya --collection aditya --type json --file "c:\restaurants
(1).json"
1.

3.

2.

5
6.

7.

8.

9.

10.

11.
13

14.

15.

16
17.

18.

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.

Query:

db.rest1.find( {"borough" :{$nin :["Staten Island","Queens","Bronx","Brooklyn"]}}, {


"restaurant_id" : 1, "name":1,"borough":1, "cuisine" :1 } );

OUTPUT:
20.

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.Write

Query:

db.rest1.find({"grades.score":{$lte:10}},{"restaurant_id":1,"cuisine":1,"name":1,"borough":1})

OUTPUT:

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'

Query:

> db.rest1.find( {$or: [ {name: /^Wil/}, {"$and": [ {"cuisine" : {$ne :"American "}},
{"cuisine" : {$ne :"Chinees"}} ]} ]} ,{"restaurant_id" : 1,"name":1,"borough":1,"cuisine" :1} );
OUTPUT:

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 survey dates.

Query:
db.rest1.find( { "grades.date": ISODate("2014-08-11T00:00:00Z"),
"grades.grade":"A" , "grades.score" : 11 }, {"restaurant_id" :
1,"name":1,"grades":1} );

OUTPUT:

23.
PRACTICAL 4

A) Write a MongoDB query to create Replica of existing database


PROCESS AS FOLLOWS:

Open in administrator mode.

Bin folder

After going into the bin folder we firstly instantiate 3 mongod replicated servers.

COMMAND:
C:\Program Files\MongoDB\Server\4.0\bin>start mongod --logpath \data\db1\1.log --dbpath
\data\db1 --port 27020 --smallfiles --oplogSize 64 --replSet MyRep

C:\Program Files\MongoDB\Server\4.0\bin>start mongod --logpath \data\db2\1.log --dbpath


\data\db2 --port 27021 --smallfiles --oplogSize 64 --replSet MyRep

C:\Program Files\MongoDB\Server\4.0\bin>start mongod --logpath \data\db3\1.log --dbpath


\data\db3 --port 27022 --smallfiles --oplogSize 64 --replSet MyRep
After in another terminal we have to go firstly into the bin folder and then in that we have to
start each client in a new terminal associated with that terminal.

COMMAND: mongo –port [port no of server][27020]


var config={_id:"MyRep",members:[{_id:0,host:"localhost:27020"},{_id:1,host:"localhost:27021"}]}
rs.initiate(config)

In the rest of terminals only the port will change and as we are making them as secondaries
so we have made them as slaves.
For this COMMAND: rs.slaveOk()
rs.secondaryOk()

After that once all the above process is done you will be able see written as primary in first
server if not press enter onto it

After once all is done it means you have successfully created a replica set.

Now you can perform various operations onto it.


Fire various queries onto it and see if you are consistent results or not.
PRACTICAL 3

1. Write a MongoDB query to use sum, avg, min and max expression

CODE:

> use aditya23


switched to db aditya23
> db.createCollection("agg")
{ "ok" : 1 }
> show collecttions
2023-08-17T14:39:51.177+0530 E QUERY [js] Error: don't know how to show [collecttions]
:
shellHelper.show@src/mongo/shell/utils.js:1066:11
shellHelper@src/mongo/shell/utils.js:766:15
@(shellhelp2):1:1
> show collections
agg
> db.createCollection("my collection")
{ "ok" : 1 }
> db.my collection.insert({"title":"practicalMongodb","Description":"Mongodb is an NOSQL
Database","url":"www.practicalmongodb.com","by":"shakuntala","tags":["auth","kam","mal","p
aoen"],"comments":["user":"aditya","message":"very good
book","date":17-04-2023,"like":23]})
2023-08-17T15:04:43.961+0530 E QUERY [js] SyntaxError: missing ; before statement
@(shell):1:6
> db.createCollection("mycollection")
{ "ok" : 1 }
> db.mycollection.insert({"title":"practicalMongodb","Description":"Mongodb is an NOSQL
Database","url":"www.practicalmongodb.com","by":"shakuntala","tags":["auth","kam","mal","p
aoen"],"comments":["user":"aditya","message":"very good
book","date":17-04-2023,"like":23]})
2023-08-17T15:06:41.784+0530 E QUERY [js] SyntaxError: missing ] after element list
@(shell):1:201
> db.mycollection.insert({"title":"practicalMongodb","Description":"Mongodb is an NOSQL
Database","url":"www.practicalmongodb.com","by":"shakuntala","tags":["auth","kam","mal","p
aoen"],"comments":{"user":"aditya","message":"very good
book","date":17-04-2023,"like":23}})
WriteResult({ "nInserted" : 1 })
> db.mycollection.insert({"title":"practicalMongodb","Description":"Mongodb is an NOSQL
Database","url":"www.practicalmongodb.com","by":"shakuntala","tags":["auth","kam","mal","p
aoen"],"likes":24,"comments":{"user":"aditya","message":"very good
book","date":17-04-2023,"like":1}})
WriteResult({ "nInserted" : 1 })
> db.mycollection.insert({"title":"Wings of fire","Description":"the book is
historic","url":"www.wof.com","by":"ABP abdul
kalam","tags":["auth","kam","mal","paoen"],"likes":34,"comments":{"user":"asmita","message"
:"good book","date":18-04-2034,"like":1}})
WriteResult({ "nInserted" : 1 })
> db.mycollection.insert({"title":"SPM","Description":"software project
management","url":"www.as.com","by":"Meghana
bhatia","tags":["auth","kam","mal","paoen"],"likes":13,"comments":{"user":"zuber","message":
"Excellent summary","date":18-05-2002,"like":1}})
WriteResult({ "nInserted" : 1 })
> db.mycollection.insert({"title":"AWP","Description":"Advanced web
programming","url":"www.awp.com","by":"Nutan
Maam","tags":["auth","kam","mal","paoen"],"likes":24,"comments":{"user":"smita","message":"
Excellent BOOK","date":12-03-2012,"like":1}})
WriteResult({ "nInserted" : 1 })
>
db.mycollection.insert({"title":"asd","Description":"hjkjfkjsf","url":"www.asm34.com","by":"ASM
ITA","tags":["auth","kam","mal","paoen"],"likes":33,"comments":{"user":"smitaL","message":"E
xcellent23 BOOK","date":12-03-2022,"like":1}})
WriteResult({ "nInserted" : 1 })

OPERATIONS

> db.mycollection.aggregate([{$group:{_id:"$by_user",num_likes:{$sum:"$likes"}}}])
{ "_id" : null, "num_likes" : 128 }
> db.mycollection.aggregate([{$group:{_id:"$by_user",num_likes:{$avg:"$likes"}}}])
{ "_id" : null, "num_likes" : 25.6 }
> db.mycollection.aggregate([{$group:{_id:"$by_user",num_likes:{$min:"$likes"}}}])
{ "_id" : null, "num_likes" : 13 }
> db.mycollection.aggregate([{$group:{_id:"$by_user",num_likes:{$max:"$likes"}}}])
{ "_id" : null, "num_likes" : 34 }

.
2. Write a MongoDB query to use push and addToSet expression

CODE:

> db.mycollection.aggregate([{$group:{_id:"$by_user",asm:{$push:"$url"}}}])
{ "_id" : null, "asm" : [ "www.practicalmongodb.com", "www.practicalmongodb.com",
"www.wof.com", "www.as.com", "www.awp.com", "www.asm34.com" ] }
> db.mycollection.aggregate([{$group:{_id:"$by_user",as34:{$addToSet:"$url"}}}])
{ "_id" : null, "as34" : [ "www.asm34.com", "www.wof.com", "www.practicalmongodb.com",
"www.awp.com", "www.as.com" ] }

PRACTICAL 5

PROCEDURE:

NGT PRACTICAL 5
Practical 5 mongodb and Java
Jar file for that
Java program to communicate to a database
We require a driver fil
Driver required -Mongo Java driver 3.12.14 = download from internet

1.environmental.variables
User variables
System variables-we edit
Path variables-files we need for our application
Cick on path- edit - (no have settled)-new- paste the path(go to bin)-ok our path set

Set the class path - create a new var- var name: class path, value: ".;(where path of har file
along with name);"-ok
Setting is in placed
JAVA PROGRAM
4 PROGRAMS - 40 marks
Explaination
Creating the data
Import statement
4 lines com.mongodb.client - packages available on jar file
Classes- mongocollection,mongodatabase,mongoclient,mongocredential
Org.bson.document- org.bson packages

1.our mongo client should be create and listen to database server


2 parameters string,long no
2. Specify the database- connected to the database
If mydb6 is available then open otherwise create new one
3. Specify the collection
Document datatype stored
If available then open or not then create
4.insert the data
Document object
Collection is now reffering to sample collection1

EXECUTION PART
BIN FOLDER>mongod
Mongo
Another cmd in administrator mode
Move to location of Java program
Type>javac insertingdoc.java
Type>java Inserting document
In mongo
>Show dbs
>use mydb6
>Show Collections
Go to collection and find() execute

DELETING,UPDATION,READING COLLECTIONS FROM A DATABASE

RETRIEVING FROM DATABASE


import java.util.iterator
Com.mongoclient.Finditreable
Because you don't know how many collections are there so we should use iterator for it

CODE:
hasNext()- till next value is available- either true or false
UPDATION IN OUR COLLECTION
com.mongodb.DB
DBCollection,DBObject,WriteResult(able to update or not)
DB db = mongo.getDB(If not available then it will not create the database)
query- which data should be updated
Update.put = make changes

DELETION COLLN
Com.
Filters- which collection needed to be updated

Java with Mongodb


import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;

import org.bson.Document;

public class InsertingDocument23


{
public static void main(String args[])
{
MongoClient mongo = new MongoClient("localhost", 27017); // Creating a Mongo
client
System.out.println("Connected to the database successfully");

MongoDatabase database= mongo.getDatabase("mytdb"); // Accessing the


database

MongoCollection<Document> collection=
database.getCollection("sampleCollection"); // Accessing the collection

Document document = new Document();


document.append("id",1);
document.append("description", "database");
document.append("likes", 100);
document.append("url", "http://www.MongoDb.com");
document.append("by", "NoSQL");

collection.insertOne(document);

System.out.println("Document inserted successfully");


}
}

jQuery practical:

<!doctype html>
<html>
<head>
<title>Online jQuery Editor</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("p").css("background-color", "yellow");
$("button").click(function(){document.write("Hello World")});
$(".class1").css("background-color", "red");
$("#id1").css("background-color", "blue");
$("h1").css("background-color", "purple");
$(".c2").css("background-color", "red");
});
</script>
</head>
<body>
<h1>jQuery element Selector</h1>
<p class="class1">Using of class attribute</p>
<p id="id1">This is p tag</p>
<button class="c2">Click Here</button>
</body>
</html>

<!doctype html>
<html>
<head>
<title>Online jQuery Editor</title>
<script src="https://www.tutorialspoint.com/jquery/jquery-3.6.0.js"></script>
<script>
$(document).ready(function() {
$("p").css("background-color", "yellow");
$("button").click(function(){document.write("Hello World")});
$(".class1").css("background-color", "red");
$("#id1").css("background-color", "blue");
$("h1").css("background-color", "purple");

});
</script>
</head>
<body>
<h1>jQuery element Selector</h1>
<p class="class1">Using of class attribute</p>
<p id="id1">This is p tag</p>
<button class="b1">hover</button>
<p> Hello Students</p>
<p>TyIT</p>
<button id="b2">off</button>
<p id="t1">hello</p>

</body>
</html>

You might also like