NOSQL Lab Book
NOSQL Lab Book
Name: ________________________________________________________________
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
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.
Advantages of MongoDB :
Disadvantages of MongoDB :
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
If you want to check your databases list, use the command show dbs.
>show dbs
local 0.78125GB
test 0.23012GB
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
>
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.
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
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
>
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.
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")
}
>
Syntax
>db.COLLECTION_NAME.find().pretty()
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"
}
>
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})
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})
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
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
Remark: ___________
NEO4J Databases
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.
CQL Operators
1 Mathematical +, -, *, /, %, ^
4 String +
6 Regular =-
Expression
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)
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)
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.
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.
Creating Relationships
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.
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.
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
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.
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”.
Removing a Property
Count
Example
Following is a sample Cypher Query which demonstrates the usage of
the count() function.
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
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
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:
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 “ …….”
Queries
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.
Remark: ___________