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

NOSQL Lab Book

Uploaded by

7548n29wn6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

NOSQL Lab Book

Uploaded by

7548n29wn6
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

INDIRA COLLEGE OF COMMERCE AND SCIENCE

NOSQL DATABASES (MongoDB & Neo4j)


TYBSc (Cyber Security)

Name: ________________________________________________________________

Roll No. __________ Academic Year: _______________

Internal Examiner: --------------------- External Examiner: ---------------------

Prepared by: Miss Sarita Byagar

About The Workbook


1. Covers the scope of the course.
3. Continuous assessment of the students.
4. Providing ready references for students while working in the lab.

How to use this book?


This book is mandatory for the completion of the laboratory course.
It is a Measure of the performance of the student in the laboratory for the entire
duration of the course.
Instructions to the students
1) Students should carry this book during practical sessions of Computer Science.

2) Students should read the topics mentioned in reading section of this Book before
coming for practical.
4) Students should solve all exercises which are selected by Practical in-charge as a
part of journal activity.
Sr. No Assignment Sign
1 Assignment 1

2 Assignment 2
MongoDB
3 Assignment 3

4 Assignment 4

5 Assignment 1

6 Assignment 2
Neo4j
7 Assignment 3

8 Assignment 4
MONGO DB

MongoDB is an open-source document-oriented database that is


designed to store a large scale of data and also allows you to work with
that data very efficiently. It is categorized under the NoSQL (Not only SQL)
database because the storage and retrieval of data in the MongoDB are
not in the form of tables.

Features of MongoDB –
 Schema-less Database: It is the great feature provided by the MongoDB.
A Schema-less database means one collection can hold different types of
documents in it. Or in other words, in the MongoDB database, a single
collection can hold multiple documents and these documents may consist of
the different numbers of fields, content, and size. It is not necessary that the
one document is similar to another document like in the relational databases.
Due to this cool feature, MongoDB provides great flexibility to databases.

 Document Oriented: In MongoDB, all the data stored in the documents


instead of tables like in RDBMS. In these documents, the data is stored in
fields (key-value pair) instead of rows and columns which make the data
much more flexible in comparison to RDBMS. And each document contains
its unique object id.

 Indexing: In MongoDB database, every field in the documents is indexed


with primary and secondary indices this makes easier and takes less time to
get or search data from the pool of the data. If the data is not indexed, then
database search each document with the specified query which takes lots of
time and not so efficient.

 Scalability: MongoDB provides horizontal scalability with the help of


sharding. Sharding means to distribute data on multiple servers, here a large
amount of data is partitioned into data chunks using the shard key, and these
data chunks are evenly distributed across shards that reside across many
physical servers. It will also add new machines to a running database.
 Replication: MongoDB provides high availability and redundancy with the
help of replication, it creates multiple copies of the data and sends these
copies to a different server so that if one server fails, then the data is retrieved
from another server.

 Aggregation: It allows to perform operations on the grouped data and get a


single result or computed result. It is similar to the SQL GROUPBY clause. It
provides three different aggregations i.e, aggregation pipeline, map-reduce
function, and single-purpose aggregation methods

 High Performance: The performance of MongoDB is very high and data


persistence as compared to another database due to its features like
scalability, indexing, replication, etc.

Advantages of MongoDB :

 It is a schema-less NoSQL database. You need not to design the schema of


the database when you are working with MongoDB.
 It does not support join operation.
 It provides great flexibility to the fields in the documents.
 It contains heterogeneous data.
 It provides high performance, availability, scalability.
 It supports Geospatial efficiently.
 It is a document oriented database and the data is stored in BSON
documents.
 It also supports multiple document ACID transition (string from MongoDB
4.0).
 It does not require any SQL injection.
 It is easily integrated with Big Data Hadoop

Disadvantages of MongoDB :

 It uses high memory for data storage.


 You are not allowed to store more than 16MB data in the documents.
 The nesting of data in BSON is also limited you are not allowed to nest data
more than 100 levels.
 Creating a database in Mongodb

The use Command


MongoDB use DATABASE_NAME is used to create database. The command will
create a new database if it doesn't exist, otherwise it will return the existing
database.
Syntax
Basic syntax of use DATABASE statement is as follows −
use DATABASE_NAME

Example
If you want to use a database with name <mydb>, then use
DATABASE statement would be as follows −
>use mydb
switched to db mydb

To check your currently selected database, use the command db


>db
mydb

If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB

The dropDatabase() Method


MongoDB db.dropDatabase() command is used to drop a existing database.
Syntax
Basic syntax of dropDatabase() command is as follows −
db.dropDatabase()
This will delete the selected database. If you have not selected any database,
then it will delete default 'test' database.

Example
First, check the list of available databases by using the command, show dbs.
>show dbs
local 0.78125GB
mydb 0.23012GB
test 0.23012GB
>
If you want to delete new database <mydb>, then dropDatabase() command
would be as follows −
>use mydb
switched to db mydb
>db.dropDatabase()
>{ "dropped" : "mydb", "ok" : 1 }
>
Now check list of databases.
>show dbs
local 0.78125GB
test 0.23012GB
>

The createCollection() Method


MongoDB db.createCollection(name, options) is used to create collection.

Syntax
Basic syntax of createCollection() command is as follows −
db.createCollection(name, options)
In the command, name is name of collection to be created. Options is a
document and is used to specify configuration of collection.

Parameter Type Description

Name String Name of the collection to be created

Options Document (Optional) Specify options about


memory size and indexing

Options parameter is optional, so you need to specify only the name of the
collection. Following is the list of options you can use −
Field Type Description

(Optional) If true, enables a capped collection. Capped


collection is a fixed size collection that automatically
capped Boolean overwrites its oldest entries when it reaches its
maximum size. If you specify true, you need to
specify size parameter also.

(Optional) If true, automatically create index on _id


autoIndexId Boolean
field.s Default value is false.

(Optional) Specifies a maximum size in bytes for a


size number capped collection. If capped is true, then you need to
specify this field also.

(Optional) Specifies the maximum number of


max number
documents allowed in the capped collection.

While inserting the document, MongoDB first checks size field of capped
collection, then it checks max field.

Examples
Basic syntax of createCollection() method without options is as follows −
>use test
switched to db test
>db.createCollection("mycollection")
{ "ok" : 1 }
>
You can check the created collection by using the command show collections.
>show collections
mycollection
system.indexes

The following example shows the syntax of createCollection() method with few
important options −
> db.createCollection("mycol", { capped : true, autoIndexID : true, size : 6142800,
max : 10000 } ){
"ok" : 0,
"errmsg" : "BSON field 'create.autoIndexID' is an unknown field.",
"code" : 40415,
"codeName" : "Location40415"
}
>
In MongoDB, you don't need to create collection. MongoDB creates collection
automatically, when you insert some document.
>db.tutorialspoint.insert({"name" : "tutorialspoint"}),
WriteResult({ "nInserted" : 1 })
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>

The drop() Method


MongoDB's db.collection.drop() is used to drop a collection from the database.

Syntax
Basic syntax of drop() command is as follows −
db.COLLECTION_NAME.drop()
Example
First, check the available collections into your database mydb.
>use mydb
switched to db mydb
>show collections
mycol
mycollection
system.indexes
tutorialspoint
>
Now drop the collection with the name mycollection.
>db.mycollection.drop()
true
>
Again check the list of collections into database.
>show collections
mycol
system.indexes
tutorialspoint
>
drop() method will return true, if the selected collection is dropped successfully,
otherwise it will return false.
The insert() Method
To insert data into MongoDB collection, you need to use
MongoDB's insert() or save() method.

Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insert(document)
Example
> db.users.insert({
... _id : ObjectId("507f191e810c19729de860ea"),
... title: "MongoDB Overview",
... description: "MongoDB is no sql database",
... by: "tutorials point",
... url: "http://www.tutorialspoint.com",
... tags: ['mongodb', 'database', 'NoSQL'],
... likes: 100
... })
WriteResult({ "nInserted" : 1 })
>
Here mycol is our collection name, as created before. If the collection doesn't
exist in the database, then MongoDB will create this collection and then insert a
document into it.
In the inserted document, if we don't specify the _id parameter, then MongoDB
assigns a unique ObjectId for this document.
_id is 12 bytes hexadecimal number unique for every document in a collection.
12 bytes are divided as follows −
_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes
incrementer)
You can also pass an array of documents into the insert() method as shown
below:.
> db.createCollection("post")
> db.post.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
}
]
}
])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 2,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
>
To insert the document you can use db.post.save(document) also. If you don't
specify _id in the document then save() method will work same
as insert() method. If you specify _id then it will replace whole data of document
containing _id as specified in save() method.

The insertOne() method


If you need to insert only one document into a collection you can use this
method.

Syntax
The basic syntax of insert() command is as follows −
>db.COLLECTION_NAME.insertOne(document)

Example
Following example creates a new collection named empDetails and inserts a
document using the insertOne() method.
> db.createCollection("empDetails")
{ "ok" : 1 }
> db.empDetails.insertOne(
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9848022338"
})
{
"acknowledged" : true,
"insertedId" : ObjectId("5dd62b4070fb13eec3963bea")
}
>

The insertMany() method


You can insert multiple documents using the insertMany() method. To this
method you need to pass an array of documents.
Example
Following example inserts three different documents into the empDetails
collection using the insertMany() method.
> db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Date_Of_Birth: "1995-09-26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Date_Of_Birth: "1990-02-16",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5dd631f270fb13eec3963bed"),
ObjectId("5dd631f270fb13eec3963bee"),
ObjectId("5dd631f270fb13eec3963bef")
]
}
>

The find() Method


To query data from MongoDB collection, you need to use
MongoDB's find() method.
Syntax
The basic syntax of find() method is as follows −
>db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.
Example
Assume we have created a collection named mycol as −
> use sampleDB
switched to db sampleDB
> db.createCollection("mycol")
{ "ok" : 1 }
>
And inserted 3 documents in it using the insert() method
Following method retrieves all the documents in the collection −
> db.mycol.find()
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database", "by" : "tutorials point", "url" :
"http://www.tutorialspoint.com", "tags" : [ "mongodb", "database", "NoSQL" ],
"likes" : 100 }
{ "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "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" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
>
The pretty() Method
To display the results in a formatted way, you can use pretty() method.

Syntax
>db.COLLECTION_NAME.find().pretty()

RDBMS Where Clause Equivalents in MongoDB


To query the document on the basis of some condition, you can use following
operations.

Operation Syntax Example RDBMS


Equivalent

Equality {<key>:{$eg;<value>}} db.mycol.find({"by":"tutorials where by =


point"}).pretty() 'tutorials
point'

Less Than {<key>:{$lt:<value>}} db.mycol.find({"likes":{$lt:50}}).pretty() where likes


< 50

Less Than {<key>:{$lte:<value>}} db.mycol.find({"likes":{$lte:50}}).pretty() where likes


Equals <= 50

Greater {<key>:{$gt:<value>}} db.mycol.find({"likes":{$gt:50}}).pretty() where likes


Than > 50

Greater {<key>:{$gte:<value>}} db.mycol.find({"likes":{$gte:50}}).pretty() where likes


Than >= 50
Equals

Not {<key>:{$ne:<value>}} db.mycol.find({"likes":{$ne:50}}).pretty() where likes


Equals != 50

Values in {<key>:{$in:[<value1>, db.mycol.find({"name":{$in:["Raj", Where


an array <value2>,……<valueN>]}} "Ram", "Raghu"]}}).pretty() name
matches
any of the
value in
:["Raj",
"Ram",
"Raghu"]

Values {<key>:{$nin:<value>}} db.mycol.find({"name":{$nin:["Ramu", Where


not in an "Raghav"]}}).pretty() name
array values is
not in the
array
:["Ramu",
"Raghav"]
or, doesn’t
exist at all

AND in MongoDB
Syntax
To query documents based on the AND condition, you need to use $and keyword.
Following is the basic syntax of AND −
>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] })
Example
Following example will show all the tutorials written by 'tutorials point' and
whose title is 'MongoDB Overview'.
> db.mycol.find({$and:[{"by":"tutorials point"},{"title": "MongoDB
Overview"}]}).pretty()
{
"_id" : ObjectId("5dd4e2cc0821d3b44607534c"),
"title" : "MongoDB Overview",
"description" : "MongoDB is no SQL database",
"by" : "tutorials point",
"url" : "http://www.tutorialspoint.com",
"tags" : [
"mongodb",
"database",
"NoSQL"
],
"likes" : 100
}
>
For the above given example, equivalent where clause will be ' where by =
'tutorials point' AND title = 'MongoDB Overview' '. You can pass any number
of key, value pairs in find clause.

OR in MongoDB
Syntax
To query documents based on the OR condition, you need to use $or keyword.
Following is the basic syntax of OR −
>db.mycol.find(
{
$or: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will show all the tutorials written by 'tutorials point' or whose
title is 'MongoDB Overview'.
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>

Using AND and OR Together


Example
The following example will show the documents that have likes greater than 10
and whose title is either 'MongoDB Overview' or by is 'tutorials point'. Equivalent
SQL where clause is 'where likes>10 AND (by = 'tutorials point' OR title =
'MongoDB Overview')'
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"},
{"title": "MongoDB Overview"}]}).pretty()
{
"_id": ObjectId(7df78ad8902c),
"title": "MongoDB Overview",
"description": "MongoDB is no sql database",
"by": "tutorials point",
"url": "http://www.tutorialspoint.com",
"tags": ["mongodb", "database", "NoSQL"],
"likes": "100"
}
>
NOR in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword.
Following is the basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$not: [
{key1: value1}, {key2:value2}
]
}
)
Example
Assume we have inserted 3 documents in the collection empDetails as shown
below −
db.empDetails.insertMany(
[
{
First_Name: "Radhika",
Last_Name: "Sharma",
Age: "26",
e_mail: "[email protected]",
phone: "9000012345"
},
{
First_Name: "Rachel",
Last_Name: "Christopher",
Age: "27",
e_mail: "[email protected]",
phone: "9000054321"
},
{
First_Name: "Fathima",
Last_Name: "Sheik",
Age: "24",
e_mail: "[email protected]",
phone: "9000054321"
}
]
)
Following example will retrieve the document(s) whose first name is not
"Radhika" and last name is not "Christopher"
> db.empDetails.find(
{
$nor:[
40
{"First_Name": "Radhika"},
{"Last_Name": "Christopher"}
]
}
).pretty()
{
"_id" : ObjectId("5dd631f270fb13eec3963bef"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "[email protected]",
"phone" : "9000054321"
}

NOT in MongoDB
Syntax
To query documents based on the NOT condition, you need to use $not keyword
following is the basic syntax of NOT −
>db.COLLECTION_NAME.find(
{
$NOT: [
{key1: value1}, {key2:value2}
]
}
).pretty()
Example
Following example will retrieve the document(s) whose age is not greater than 25
> db.empDetails.find( { "Age": { $not: { $gt: "25" } } } )
{
"_id" : ObjectId("5dd6636870fb13eec3963bf7"),
"First_Name" : "Fathima",
"Last_Name" : "Sheik",
"Age" : "24",
"e_mail" : "[email protected]",
"phone" : "9000054321"
}
MongoDB Update() Method
The update() method updates the values in the existing document.

Syntax
The basic syntax of update() method is as follows −
>db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA)
Example
Consider the mycol collection has the following data.
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"MongoDB Overview"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
Following example will set the new title 'New MongoDB Tutorial' of the
documents whose title is 'MongoDB Overview'.
>db.mycol.update({'title':'MongoDB Overview'},{$set:{'title':'New MongoDB Tutorial'}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>db.mycol.find()
{ "_id" : ObjectId(5983548781331adf45ec5), "title":"New MongoDB Tutorial"}
{ "_id" : ObjectId(5983548781331adf45ec6), "title":"NoSQL Overview"}
{ "_id" : ObjectId(5983548781331adf45ec7), "title":"Tutorials Point Overview"}
>
By default, MongoDB will update only a single document. To update multiple
documents, you need to set a parameter 'multi' to true.
>db.mycol.update({'title':'MongoDB Overview'},
{$set:{'title':'New MongoDB Tutorial'}},{multi:true})

MongoDB findOneAndUpdate() method


The findOneAndUpdate() method updates the values in the existing document.

Syntax
The basic syntax of findOneAndUpdate() method is as follows −
>db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA,
UPDATED_DATA)

db.empDetails.findOneAndUpdate(
{First_Name: 'Radhika'},
{ $set: { Age: '30',e_mail: '[email protected]'}}
)
The remove() Method
MongoDB's remove() method is used to remove a document from the collection.
remove() method accepts two parameters. One is deletion criteria and second is
justOne flag.
 deletion criteria − (Optional) deletion criteria according to documents will
be removed.
 justOne − (Optional) if set to true or 1, then remove only one document.
Syntax
Basic syntax of remove() method is as follows −
>db.COLLECTION_NAME.remove(DELLETION_CRITTERIA)
Example
Consider the mycol collection has the following data.
{_id : ObjectId("507f191e810c19729de860e1"), title: "MongoDB Overview"},
{_id : ObjectId("507f191e810c19729de860e2"), title: "NoSQL Overview"},
{_id : ObjectId("507f191e810c19729de860e3"), title: "Tutorials Point Overview"}
Following example will remove all the documents whose title is 'MongoDB
Overview'.
>db.mycol.remove({'title':'MongoDB Overview'})
WriteResult({"nRemoved" : 1})

Remove Only One


If there are multiple records and you want to delete only the first record, then
set justOne parameter in remove() method.
>db.COLLECTION_NAME.remove(DELETION_CRITERIA,1)

Remove All Documents


If you don't specify deletion criteria, then MongoDB will delete whole documents
from the collection. This is equivalent of SQL's truncate command.
> db.mycol.remove({})
WriteResult({ "nRemoved" : 2 })
> db.mycol.find()
>
Assignment 1
1. Create a database with the name ‘Movie’.

2. A ‘Film’ is a collection of documents with the following fields:


a. Film Id
b. Title of the film
c. Year of release
d. Genre / Category (like adventure, action, sci-fi, romantic etc.) A film can
belong to more than one genre.
e. Actors (First name and Last name) A film can have more than one actor.
f. Director (First name and Last name) A film can have more than one director.
g. Release details (It consists of places of release, dates of release and rating of
the film.)

3. An ‘Actor’ is a collection of documents with the following fields:


a. Actor Id
b. First name
c. Last Name
d. Address (Street, City, State, Country, Pin-code)
e. Contact Details (Email Id and Phone No) f. Age of an actor.

Queries:
1. Insert at least 10 documents in the collection Film –
a) Insert at least one document with film belonging to two genres.
b) Insert at least one document with film that is released at more than one
place and on two different dates.
c) Insert at least three documents with the films released in the same year.
d) Insert at least two documents with the films directed by one director.
e) Insert at least two documents with films those are acted by a pair
‘Madhuri Dixit’ and ‘Shahrukh Khan’.
2. Insert at least 10 documents in the collection Actor. Make sure, you are
inserting the names of actors who have acted in films, given in the ‘Film’
collection.
3. Display all the documents inserted in both the collections.
4. Add a value to the rating of the film whose title starts with ‘T’.
5. Add an actor named " " in the ‘Actor’ collection. Also add the details of the
film in ‘Film’ collection in
which this actor has acted in.
6. Delete the film " ".
7. Delete an actor named " ".
8. Delete all actors from an ‘Actor’ collection who have age greater than “ ”
9. Update the actor’s address where Actor Id is “ ”.
10.Update the genre of the film directed by “ ”.
Assignment 2
1. Create a database with name ‘Company’.
2. An ‘Employee’ is a collection of documents with the following fields:
a) Employee ID
b) First Name
c) Last Name
d) Email
e) Phone No.
f) Address (House No, Street, City, State, Country, Pin-code)
g) Salary
h) Designation
i) Experience
j) Date of Joining
k) Birthdate
3. A ‘Transaction’ is a collection of documents with the following fields:
a) Transaction Id,
b) Transaction Date
c) Name (First Name of employee who processed the transaction)
d) Transaction Details (Item Id, Item Name, Quantity, Price)
e) Payment (Type of Payment (Debit/Credit/Cash), Total amount paid,
Payment Successful)
f) Remark (Remark field can be empty.)
Queries:
1. Insert at least 5 documents in ‘Employee’ collection.
2. Insert multiple documents (at least 10) into the ‘Transaction’ collection
by passing an array of documents to the db.collection.insert () method.
3. Display all the documents of both the collections in a formatted manner.
4. Update salary of all employees by giving an increment of Rs. 4000.
5. Update the remark for transaction id 201.
6. Update designation of an employee named “_ ” from supervisor to
manager.
7. Update designation of an employee having Employee Id as .
8. Change the address of an employee having Employee Id as .
9. Delete transaction made by “ ” employee on the given date.
10. 10.Delete all the employees whose first name starts with ‘K’.
Assignment 3

This assignment is based on ‘Movie’ database having collections ‘Film’ and


‘Actor’.
Note: It is expected that student should fill in the data relevant to the queries
given in the assignment. The result set should not be empty.

1. Find the titles of all the films starting with the letter ‘R’ released during the
year 2009 and 2011.
2. Find the list of films acted by an actor " ".
3. Find all the films released in 90s.
4. Find all films belonging to “Adventure” and “Thriller” genre.
5. Find all the films having ‘A’ rating.
6. Arrange the film names in ascending order and release year should be in
descending order.
7. Sort the actors in ascending order according to their age.
8. Find movies that are comedies or dramas and are released after 2013.
9. Show the latest 2 films acted by an actor “ ”.
10.List the titles of films acted by actors “ ” and “ ”.
11.Retrieve films with an actor living in Spain.
12.Retrieve films with actor details.

Assignment 4
Consider Student Database
Create a collection with the following fields : (SRN, Sname, Degree, Sem, CGPA)
Insert at least 10 documents.

Queries:
1.Display all the documents
2.Display all the students in BCA
3.Display all the students in ascending order
4.Display first 5 students
5.list the degree of student "Rahul"
6.Display the number of students in BCA
7.Display all the degrees without _id
8.Display all the distinct degrees
9.Display all the BCA students with CGPA greater than 6, but less than 7.5
10.Display all the students in BCA and in 6th Sem

Signature of the instructor: ____________________ Date: _____________

Remark: ___________
NEO4J Databases

Neo4j Property Graph Data Model


Neo4j Graph Database follows the Property Graph Model to store and
manage its data.
Following are the key features of Property Graph Model −
 The model represents data in Nodes, Relationships and Properties
 Properties are key-value pairs
 Nodes are represented using circle and Relationships are represented
using arrow keys
 Relationships have directions: Unidirectional and Bidirectional
 Each Relationship contains "Start Node" or "From Node" and "To Node" or
"End Node"
 Both Nodes and Relationships contain properties
 Relationships connects nodes

Neo4j CQL
 Is a query language for Neo4j Graph Database.
 Is a declarative pattern-matching language.
 Follows SQL like syntax.
 Syntax is very simple and in human readable format.

Neo4j CQL Data Types

Sr CQL Data Type Usage


.N
o

1 Boolean It is used to represent Boolean literals: true, false.

2 byte It is used to represent 8-bit integers.


3 short It is used to represent 16-bit integers.

4 int It is used to represent 32-bit integers.

5 long It is used to represent 64-bit integers.

6 float It is used to represent 32-bit floating-point


numbers.

7 double It is used to represent 64-bit floating-point


numbers.

8 char It is used to represent 16-bit characters.

9 String It is used to represent Strings.

CQL Operators

Sr.No Type Operators

1 Mathematical +, -, *, /, %, ^

2 Comparison +, <>, <, >, <=, >=

3 Boolean AND, OR, XOR, NOT

4 String +

5 List +, IN, [X], [X…..Y]

6 Regular =-
Expression

7 String STARTS WITH, ENDS WITH,


matching CONSTRAINTS
Creating a Node with a Label

A label in Neo4j is used to group (classify) the nodes using labels. You can create
a label for a node in Neo4j using the CREATE clause.
Syntax
Following is the syntax for creating a node with a label using Cypher Query
Language.
CREATE (node:label)
Example
Following is a sample Cypher Query which creates a node with a label.
CREATE (Dhawan:player)

Creating a Node with Multiple Labels

You can also create multiple labels for a single node. You need to specify the
labels for the node by separating them with a colon “ : ”.
Syntax
Following is the syntax to create a node with multiple labels.
CREATE (node:label1:label2:. . . . labeln)
Example
Following is a sample Cypher Query which creates a node with multiple labels
in Neo4j.
CREATE (Dhawan:person:player)

Create Node with Properties

Properties are the key-value pairs using which a node stores data. You can create
a node with properties using the CREATE clause. You need to specify these
properties separated by commas within the flower braces “{ }”.
Syntax
Following is the syntax to create a node with properties.
CREATE (node:label { key1: value, key2: value, . . . . . . . . . })
Example
Following is a sample Cypher Query which creates a node with properties.

CREATE (Dhawan:player{name: "Shikar Dhawan", YOB: 1985, POB: "Delhi"})


Returning the Created Node

Syntax
Following is the syntax to return a node in Neo4j.
CREATE (Node:Label{properties. . . . }) RETURN Node
Example
Following is a sample Cypher Query which creates a node with properties and
returns it.

CREATE (Dhawan:player{name: "Shikar Dhawan", YOB: 1985, POB: "Delhi"})


RETURN Dhawan

Creating Relationships

We can create a relationship using the CREATE clause. We will specify


relationship within the square braces “[ ]” depending on the direction of the
relationship it is placed between hyphen “ - ” and arrow “ → ” as shown in the
following syntax.
Syntax
Following is the syntax to create a relationship using the CREATE clause.
CREATE (node1)-[:RelationshipType]->(node2)
Example
First of all, create two nodes Ind and Dhawan in the database, as shown below.
CREATE (Dhawan:player{name: "Shikar Dhawan", YOB: 1985, POB: "Delhi"})
CREATE (Ind:Country {name: "India"})
Now, create a relationship named BATSMAN_OF between these two nodes as −
CREATE (Dhawan)-[r:BATSMAN_OF]->(Ind)
Finally, return both the nodes to see the created relationship.
RETURN Dhawan, Ind
Creating a Relationship Between the Existing Nodes

You can also create a relationship between the existing nodes using
the MATCH clause.
Syntax
Following is the syntax to create a relationship using the MATCH clause.
MATCH (a:LabeofNode1), (b:LabeofNode2)
WHERE a.name = "nameofnode1" AND b.name = " nameofnode2"
CREATE (a)-[: Relation]->(b)
RETURN a,b
Example
Following is a sample Cypher Query which creates a relationship using the
match clause.

MATCH (a:player), (b:Country) WHERE a.name = "Shikar Dhawan" AND


b.name = "India"
CREATE (a)-[r: BATSMAN_OF]->(b)
RETURN a,b

Deleting a Particular Node

To delete a particular node, you need to specify the details of the node in the
place of “n” in the above query.
Syntax
Following is the syntax to delete a particular node from Neo4j using the DELETE
clause.
MATCH (node:label {properties . . . . . . . . . . })
DETACH DELETE node

Following is a sample Cypher Query which deletes the above created node using
the DELETE clause.

MATCH (Ishant:player {name: "Ishant Sharma", YOB: 1988, POB: "Delhi"})


DETACH DELETE Ishant
Removing a Property

You can remove a property of a node using MATCH along with the REMOVE
clause.
Syntax
Following is the syntax to remove a property of a node using the REMOVE clause.
MATCH (node:label{properties . . . . . . . })
REMOVE node.property
RETURN node
Following is a sample Cypher Query to remove the above created node using the
REMOVE clause.
MATCH (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB:
"Ranchi"})
REMOVE Dhoni.POB
RETURN Dhoni

Removing a Label From a Node

Similar to property, you can also remove a label from an existing node using the
remove clause.
Syntax
Following is the syntax to remove a label from a node.
MATCH (node:label {properties . . . . . . . . . . . })
REMOVE node:label
RETURN node
Example
Following is a sample Cypher Query to remove a label from an existing node
using the remove clause.

MATCH (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB:


"Ranchi"})
REMOVE Dhoni:player
RETURN Dhoni

Using the SET clause, you can create a new property in a node.
Syntax
Following is the syntax for setting a property.
MATCH (node:label{properties . . . . . . . . . . . . . . })
SET node.property = value
RETURN node
Following is a sample Cypher Query to create a property
named “highestscore” with value “187”.

MATCH (Dhawan:player{name: "shikar Dhawan", YOB: 1985, POB: "Delhi"})


SET Dhawan.highestscore = 187
RETURN Dhawan

Removing a Property

You can remove an existing property by passing NULL as value to it.


Syntax
Following is the syntax of removing a property from a node using the SET clause.
MATCH (node:label {properties})
SET node.property = NULL
RETURN node

Count

The count() function is used to count the number of rows.


Syntax
Following is the syntax of the count function.
MATCH (n { name: 'A' })-->(x)
RETURN n, count(*)

Example
Following is a sample Cypher Query which demonstrates the usage of
the count() function.

Match(n{name: "India", result: "Winners"})--(x)


RETURN n, count(*)

Like SQL, Neo4j CQL has provided WHERE clause in CQL MATCH command to
filter the results of a MATCH Query.
Syntax
Following is the syntax of the WHERE clause.
MATCH (label)
WHERE label.country = "property"
RETURN label
Following is a sample Cypher Query which returns all the players (nodes) that
belongs to the country India using WHERE clause.

MATCH (player)
WHERE player.country = "India"
RETURN player

WHERE Clause with Multiple Conditions

You can also use the WHERE clause to verify multiple conditions.
Syntax
Following is the syntax to use WHERE clause in Neo4j with multiple conditions.
MATCH (emp:Employee)
WHERE emp.name = 'Abc' AND emp.name = 'Xyz'
RETURN emp
Example
Following is a sample Cypher Query which filters the nodes in the Neo4j database
using two conditions.

MATCH (player)
WHERE player.country = "India" AND player.runs >=175
RETURN player

Using Relationship with Where Clause

Following is a sample Cypher Query to retrieve the top scorer of India using
WHERE clause as shown below.

MATCH (n)
WHERE (n)-[: TOP_SCORER_OF]->( {name: "India", result: "Winners"})
RETURN n
Assignments

Create the following databases as graph models. Visualize the models after
creation, Return properties of nodes, Return the nodes labels, Return the
relationships with its properties. NB: You may assume and add more labels ,
relationships, properties to the graphs
1. Create a library database , as given below.
There are individual books, readers, and authors that are present in the library
data model.. A minimal set of labels are as follows:
Book: This label includes all the books
Person: This label includes authors, translators, reviewers, Readers, Suppliers
and so on
Publisher: This label includes the publishers of books in the database
A set of basic relationships are as follows:
PublishedBy: This relationship is used to specify that a book was published by
a publisher
Votes: This relationship describes the relation between a user and a book, for
example, how a book was rated by a user.
ReviewedBy : This relationship is used to specify that a book was reviewed and
remarked by a user.
TranslatedBy: This relationship is used to specify that a book was translated to
a language by a user.
IssuedBy: This relationship is used to specify that a book was issued by a user.
ReturnedBy: This relationship is used to specify that a book was returned by a
user
Every book has the following properties:
Title: This is the title of the book in string format
Tags: This is an array of string tags useful for searching through the database
based on topic, arguments, geographic regions, languages, and so on
Status: the book status , specifying whether its issued or in library.
Condition: book condition, new or old
Cost : Cost of book Type: book is a Novel, Journal, suspense thriller etc

Queries:

a) List all people, who have issued a book “……”


b) Count the number of people who have read “ ….”
c) Add a property “Number of books issued “ for Mr. Joshi and set its value as
the count
d) List the names of publishers from pune city.
2. Consider a Song database, with labels as Artists,
Song,Recording_company, Recoding_studio, song author etc.
Relationships can be as follows
Artist→[Performs]→Song →[Written by]→Song_author.
Song →[Recorded in ] →Recording Studio →[managed by] →recordingCompany
Recording Company →[Finances] →Song
You may add more labels and relationship and their properties, as per
assumptions.

Queries :
a) List the names of songs written by “:…..”
b) List the names of record companies who have financed for the song “….”
c) List the names of artist performing the song “…..”
d) Name the songs recorded by the studio “ …….”

3. Consider an Employee database, with a minimal set of labels as follows


Employee: denotes a person as an employee of the organization
Department: denotes the different departments, in which employees work.
Skillset: A list of skills acquired by an employee
Projects: A list of projects in which an employee works.
A minimal set of relationships can be as follows:
Works_in : employee works in a department
Has_acquired: employee has acquired a skill
Assigned_to : employee assigned to a project
Controlled_by: A project is controlled by a department
Project_manager : Employee is a project_manager of a Project

Queries

a) List the names of employees in department “……..”


b) List the projects along with their properties, controlled by department “……”
c) List the departments along with the count of employees in it
d) List the skillset for an employee “…….”
4. Create a Social network database , with labels as Person, Affiliations,
Groups, Story, Timeline etc. Some of the relationships can be as follows:
Person→[friend of]→Person→[affiliated to]→affiliations
Person→[belongs to]→Groups, Person→[create]→Story→[refers to] →Person
Person→[creates]→Timeline→[reference for]→Story ,
Timeline→[contains]→Messages

Queries

a) Find all friends of “John”, along with the year, since when john knows them.
b) List out the affiliations of John.
c) Find all friends of john, who are born in the same year as John
d) List out the messages posted by John in his timeline, during the year 2015.

Signature of the instructor: ____________________ Date: _____________

Remark: ___________

You might also like