0% found this document useful (0 votes)
73 views57 pages

MongoDB Lab Manual AI DS 2024 25

The document is a laboratory manual for a MongoDB course in the Department of Computer Science and Engineering, outlining program outcomes, educational objectives, and course objectives. It includes a list of experiments, assessment details, and resources for learning MongoDB, emphasizing its advantages over traditional RDBMS. The manual also highlights the importance of MongoDB in handling big data and its flexible schema capabilities.

Uploaded by

Varshini V B
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)
73 views57 pages

MongoDB Lab Manual AI DS 2024 25

The document is a laboratory manual for a MongoDB course in the Department of Computer Science and Engineering, outlining program outcomes, educational objectives, and course objectives. It includes a list of experiments, assessment details, and resources for learning MongoDB, emphasizing its advantages over traditional RDBMS. The manual also highlights the importance of MongoDB in handling big data and its flexible schema capabilities.

Uploaded by

Varshini V B
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/ 57

DepartmentofCSE (Artificial Intelligence & Data Science)

‘JnanaPrabha’,VirgoNagarPost,Bengaluru-560049

LABORATORYMANUAL

SEMESTER : IV

SUBJECT : MONGO DB

SUBJECT CODE : BDS456B

NAME: _ _ _ _ _ _ _ _ _ _ _ _

USN: _ _ _ _ _ _ _ _ _ _ __ _

SECTION:_ _ _ _ _ _ _ _ _ _ _ _

BATCH:_ _ _ _ _ _ _ _ _ _ __ _
PROGRAM OUTCOMES

Engineering Graduates will able to:

Engineeringknowledge:Applytheknowledgeofmathematics,science,engineeringfunda
mentals, and an engineering specialization to the solution of complex engineering
problems.

Problemanalysis:Identify,formulate,reviewresearchliterature,andanalyzecomplexengi
neeringproblemsreachingsubstantiatedconclusionsusingfirstprinciplesofmathematics,na
turalsciences,andengineeringsciences.

Design/development of solutions: Design solutions for complex engineering


problems and design system components or processes that meet the specified needs
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.

Conduct investigations of complex problems: Use research-based knowledge and


research methods including design of experiments, analysis and interpretation of data,
and synthesis of the information to provide valid conclusions.

Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modernengineeringandITtoolsincludingpredictionandmodellingtocomplexengineeringa
ctivitieswithanunderstandingofthelimitations.

The engineer and society: Apply reasoning informed by the contextual knowledge to
assesssocietal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.

Environment and sustainability: Understand the impact of the professional


engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.

Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice. Individual and team work: Function effectively
as an individual, and as a memberor leader in diverseteams, and in multi disciplinary
settings.

Communication:Communicateeffectivelyoncomplexengineeringactivitieswiththeengi
neering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.

Projectmanagementandfinance:DemonstrateknowledgeandunderstandingoftheEngin
eering and management principles and apply these to one’s own work, as a member
andleaderinateam,tomanageprojectsandinmultidisciplinaryenvironments.

Lifelonglearning:
Recognizetheneedforandhavethepreparationandabilitytoengageinindependentandlife-
longlearninginthebroadestcontext of technological change.
INSTITUTE VISION AND MISSION

VISION

The East Point College of Engineering and Technology aspires to be a


globally acclaimed institution, recognized for excellence in engineering
education, applied research and nurturing students for holistic development.

MISSION

M1:To create engineering graduates through quality education and to nurture


innovation, creativity and Excellence in teaching, learning and research
M2:To
servethetechnical,scientific,economicandsocietaldevelopmentalneedsofourco
mmunities
M3: To induce integrity, teamwork, critical thinking, personality
development and ethics in students and to lay the foundation for lifelong
learning.
DepartmentofCSE (Artificial intelligence & Data Science)

DEPARTMENT VISION AND MISSION

The department orients towards identifying and exploring emerging global trends in the fields of
Artificial Intelligence and Data Science through academic excellence and quality research,
producing proficient professionals for a flourishing society.
MISSION
M1: To nurture students with quality education, life-long learning, values and ethics.
M2:To produce ethical and competent professionals through comprehensive and holistic
methodologies that align with the global industry demands in Artificial Intelligence and Data
Science.

PROGRAM EDUCATIONAL OBJECTIVES (PEOS)

PEO 1: To enable students to build Intelligent Machines and applications with a cutting –
edge combination of machine learning, analytics and visualization.

PEO 2: To enable technocrats to pursue higher education and research, and have a successful
career in industries related to AIDS.

PEO 3: To produce graduate professionals with ethics, who will contribute to industrial
growth and social transformation as responsible citizens.

PROGRAM SPECIFIC OUTCOMES (PSOS)

PSO 1: Adapt, contribute and innovate new technologies in computing profession by


working in teams to design, implement, and maintain in the key domains of Artificial
Intelligence & Data Science.

PSO 2: Apply the skills in the areas of Health care, Education, Agriculture, Environment,
Smart Systems & in the multi-disciplinary area of Artificial Intelligence & Data
Science.
MongoDB Semester 4
Course Code BDS456B CIE Marks 50
Teaching Hours/Week (L: T:P: S) 0:0:2:0 SEE Marks 50
Total Hours of Pedagogy 24 Total Marks 100
Credits 01
Course objectives:
● Understand basic MongoDB functions, operators and types of operations in MongoDB.
● Demonstrate the use of Indexing, Advanced Indexing in MongoDB.
● Apply the aggregation and Map Reduction in MongoDB.
● Demonstrate text searching on collections in MongoDB.

Sl.NO List of Experiments


1 a. Illustration of Where Clause, AND,OR operations in MongoDB.
b. Execute the Commands of MongoDB and operations in MongoDB : Insert, Query, Update,
Delete and Projection. (Note: use any collection)

2 a. Develop a MongoDB query to select certain fields and ignore some fields of the documents
from any collection.
b. Develop a MongoDB query to display the first 5 documents from the results obtained in a. [use
of limit and find]

3 a.Execute query selectors (comparison selectors, logical selectors ) and list out the results on any
collection
b. Execute query selectors (Geospatial selectors, Bitwise selectors ) and list out the results on any
collection.

4 Create and demonstrate how projection operators ($, $elematch and $slice) would be used in the
MondoDB.

5 Execute Aggregation operations ($avg, $min,$max, $push, $addToSet etc.). students encourage
to execute several queries to demonstrate various aggregation operators)

6 Execute Aggregation Pipeline and its operations (pipeline must contain $match, $group, $sort,
$project,
$skip etc. students encourage to execute several queries to demonstrate various aggregation
operators)
7 a. Find all listings with listing_url, name, address, host_picture_url in the listings And Reviews
collection that have a host with a picture url
b. Using E-commerce collection write a query to display reviews summary.
8 a. Demonstrate creation of different types of indexes on collection (unique, sparse, compound and
multikey indexes)
b. Demonstrate optimization of queries using indexes.

9 a. Develop a query to demonstrate Text search using catalog data collection for a given word
b. Develop queries to illustrate excluding documents with certain words and phrases .

10 Develop an aggregation pipeline to illustrate Text search on Catalog data collection.

Course outcomes (Course Skill Set):

At the end of the course the student will be able to:


1. Make use of MangoDB commands and queries.
2. Illustrate the role of aggregate pipelines to extract data.
3. Demonstrate optimization of queries by creating indexes.
4. Develop aggregate pipelines for text search in collections.

Assessment Details (both CIE and SEE)


The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50) and for the
SEE minimum passing mark is 35% of the maximum marks (18 out of 50 marks). A student shall
bedeemed to have satisfied the academic requirements and earned the credits allotted to each
subject/course if the student secures a minimum of 40% (40 marks out of 100) in the sum total of the
CIE(Continuous Internal Evaluation) and SEE (Semester End Examination) taken together.

Continuous Internal Evaluation (CIE):


CIE marks for the practical course are 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
● Each experiment is to be evaluated for conduction with an observation sheet and record write-up.Rubrics
for the evaluation of the journal/write-up for hardware/software experiments aredesigned by the faculty
who is handling the laboratory session and are made known to students atthe beginning of the practical
session.
● Record should contain all the specified experiments in the syllabus and each experiment write-up
will be evaluated for 10 marks.
● Total marks scored by the students are scaled down to 30 marks (60% of maximum marks).
● Weightage to be given for neatness and submission of record/write-up on time.
● Department shall conduct a test of 100 marks after the completion of all the experiments listed inthe
syllabus.
● In a test, test write-up, conduction of experiment, acceptable result, and procedural knowledge willcarry
a weightage of 60% and the rest 40% for viva-voce.
● The suitable rubrics can be designed to evaluate each student’s performance and learning ability.
● The marks scored shall be scaled down to 20 marks (40% of the maximum marks).
The Sum of scaled-down marks scored in the report write-up/journal and marks of a test is the total CIE
marks scored by the student.

Semester End Evaluation (SEE):


● SEE marks for the practical course are 50 Marks.
● SEE shall be conducted jointly by the two examiners of the same institute, examiners areappointed by
the Head of the Institute.
● The examination schedule and names of examiners are informed to the university before theconduction
of the examination. These practical examinations are to be conducted between theschedule mentioned in
the academic calendar of the University.
● All laboratory experiments are to be included for practical examination.
● (Rubrics) Breakup of marks and the instructions printed on the cover page of the answer scriptto be
strictly adhered to by the examiners. OR based on the course requirement evaluationrubrics shall be
decided jointly by examiners.
● Students can pick one question (experiment) from the questions lot prepared by the examinersjointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly
byexaminers.
● General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure andresult in
-60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for 100 marksand scored
marks shall be scaled down to 50 marks (however, based on course type, rubrics shall bedecided by the
examiners)
Change of experiment is allowed only once and 15% of Marks allotted to the procedure part are to be
made zero.
The minimum duration of SEE is 02 hours
Suggested Learning Resources:
BOOK 1: “MongoDB: The Definitive Guide”, Kristina chodorow, 2nd ed O’REILLY, 2013.
BOOK 2: “MongoDB in Action” by KYLE BANKER et. al. 2nd ed, Manning publication, 2016
BOOK3: “MongoDB Complete Guide” by Manu Sharma 1st ed, bpb publication, 2023.
Installation of MongoDB Video: https://www.youtube.com/watch?v=dEm2AS5amyA
Video on Aggregation: https://www.youtube.com/watch?v=vx1C8EyTa7Y
MongoDB in action book Code download URL: https://www.manning.com/downloads/529
MongoDB Exercise URL: https://www.w3resource.com/mongodb-exercises/
Introduction to MongoDB

What is MongoDB?
 MongoDB the most popular NoSQL database, is an open-source
document-oriented database. The term ‘NoSQL’ means ‘non-
relational’.
 It means that MongoDB isn’t based on the table-like relational
database structure but provides an altogether different mechanism
for the storage and retrieval of data. This format of storage is
called BSON ( similar to JSON format).
 SQL databases store data in tabular format. This data is stored in a
predefined data model which is not very much flexible for today’s
real-world highly growing applications.
 Modern applications are more networked, social and interactive
than ever. Applications are storing more and more data and are
accessing it at higher rates.
 Relational Database Management System(RDBMS) is not the
correct choice when it comes to handling big data by the virtue of
their design since they are not horizontally scalable. If the database
runs on a single server, then it will reach a scaling limit.
 NoSQL databases are more scalable and provide superior
performance. MongoDB is such a NoSQL database that scales by
adding more and more servers and increases productivity with its
flexible document model.

Where do we use MongoDB?


MongoDB is preferred over RDBMS in the following scenarios:
 Big Data: If we have huge amount of data to be stored in tables,
think of MongoDB before RDBMS databases. MongoDB has built-
in solution for partitioning and sharding our database.
 Unstable Schema: Adding a new column in RDBMS is hard
whereas MongoDB is schema-less. Adding a new field does not
effect old documents and will be very easy.
 Distributed data Since multiple copies of data are stored across
different servers, recovery of data is instant and safe even if there is
a hardware failure.
Language Support by MongoDB:
MongoDB currently provides official driver support for all popular
programming languages like C, C++, Rust, C#, Java, Node.js,
Perl, PHP, Python, Ruby, Scala, Go and Erlang.
Difference Between RDBMS and MongoDB

Feature RDBMS MongoDB

Type of Non-relational, document-


Relational database
Database oriented database

Stores data in tables


Stores data in flexible JSON-
Data Storage with rows and
like documents (BSON)
columns

Fixed, predefined Schema-less, dynamic


Schema
schema schema

Supports complex Does not support complex


Joins
joins joins

Data Format Row-based storage Document-based storage

Slower compared to
Faster, particularly for
Performance MongoDB for large
handling large-scale data
datasets

Less flexible for Highly flexible, suitable for


Flexibility changes in data agile development and
structure evolving data models

Backup and Backup and recovery Automated backup and


Recovery options are manual recovery options available
//to start mongo client
$ mongosh

//to list out database names


> show dbs

//to create database


> use student

//To know the Mongodb version


>db.version()

//to check in which database I am working


> db

//to drop database in which I am working


>db.dropDatabase()

//To create collection


>db.createCollection('details')

//to list out collection names


> show collections

Now drop the collection with the name mycollection


>db.details.drop()

//create collection by inserting document


>db.details.insert(
{rno:1,
name:'Bhavana',
email:'bhavana@123',
location:'delhi',
marks:80}
)
// create student details like name, rno, email,location,address,marks

//Every row/document can be different than other


>db.details.insert(
{rno:2,
name:'Amith',
email:'Amith@123',
location:'Pune',
marks:90}
)
>db.details.insert(
{rno:3,
name:'Sagar',
email:'sagar@123',
location:'Chennai',
marks:70}
)

// To display data from collection


>db.details.find()
{
_id: ObjectId('678e50018024973ccf2e3479'),
rno: 1,
name: 'Bhavana',
email: 'bhavana@123',
location: 'delhi',
marks: 80
}
{
_id: ObjectId('678e51168024973ccf2e347a'),
rno: 2,
name: 'Amith',
email: 'Amith@123',
location: 'Pune',
marks: 90
}
{
_id: ObjectId('678e51278024973ccf2e347b'),
rno: 3,
name: 'Sagar',
email: 'sagar@123',
location: 'Chennai',
marks: 70
}
Program 1
a.Illustration of Where Clause, AND, OR operations in
MongoDB.Where Clause in MongoDB:
In MongoDB, the find() method is used to query documents from
acollection. The find() method can accept a query document as a
parameter which acts as a"WHERE" clause.
Syntax:db.collection.find({ field: value })

>db.details.find()

Out Put:
{
_id: ObjectId('678e50018024973ccf2e3479'),
rno: 1,
name: 'Bhavana',
email: 'bhavana@123',
location: 'delhi',
marks: 80
}
{
_id: ObjectId('678e51168024973ccf2e347a'),
rno: 2,
name: 'Amith',
email: 'Amith@123',
location: 'Pune',
marks: 90
}
{
_id: ObjectId('678e51278024973ccf2e347b'),
rno: 3,
name: 'Sagar',
email: 'sagar@123',
location: 'Chennai',
marks: 70
}
//findOne to show only first record
>db.details.findOne()

Out Put:
{
_id: ObjectId('678e50018024973ccf2e3479'),
rno: 1,
name: 'Bhavana',
email: 'bhavana@123',
location: 'delhi',
marks: 80}
AND Operation in MongoDB:
MongoDB provides the $and operator to perform logical ANDoperation
between multiple conditions in a query.
Syntax:
db.collection.find({ $and: [ { field1: value1 }, { field2: value2 } ] })
>db.details.find({$and: [{location: "Chennai"}, {name: "Sagar"}] })

Out Put:
{
_id: ObjectId('678e51278024973ccf2e347b'),
rno: 3,
name: 'Sagar',
email: 'sagar@123',
location: 'Chennai',
marks: 70
}
OR Operation in MongoDB
: Similarly, MongoDB provides the $or operator to perform logicalOR
operation between multiple conditions in a query.
Syntax:
db.collection.find({ $or: [ { field1: value1 }, { field2: value2 } ] })
>db.details.find({$or: [{location: "Chennai"}, {location: "Bhopal"}] })

Out Put:
{
_id: ObjectId('678e51278024973ccf2e347b'),
rno: 3,
name: 'Sagar',
email: 'sagar@123',
location: 'Chennai',
marks: 70
}
Syntax:
db.collection.find({ $and: [ { field1: value1 }, { $or: [ { field2: value2 },
{ field3: value3 } ] } ] })

>db.details.find({$and:[{name:"Sagar"},{$or:[{location:"Chennai"},{loc
ation:"Pune"}]}]})
Out Put:
{
_id: ObjectId('678e51278024973ccf2e347b'),
rno: 3,
name: 'Sagar',
email: 'sagar@123',
location: 'Chennai',
marks: 70
}
In the combined example, we're using both $and and $or operators
to filter documents based on multiple conditions. Adjust the field
names and values according to your specific use case.

b. Execute the Commands of MongoDB and operations in MongoDB:


Insert, Query, Update, Deleteand Projection. (Note: use
any collection).
Insert Operation:
Use the insertOne() method to insert a single document into a collection.
Syntax:
db.collection.insertOne({ field1: value1, field2: value2, field3: value3 })
Every row/document can be different than other
>db.details.insert({
rno:1,
name:'Bhavana',
email:'bhavana@123',
location:'delhi',
marks:80
})
>db.details.insert({
rno:2,
name:'Amith',
email:'Amith@123',
location:'Pune',
marks:90}
})

// To insert date use ISODate function


>db.details.insert({
rno:15,
name:'Ravina',
dob:ISODate("2019-09-14")
})
Out put:
{
_id: ObjectId('678e6d8d8024973ccf2e347e'),
rno: 5,
name: 'Ravina',
dob: 2019-09-14T00:00:00.000Z
}

>db.details.insert({
rno:6,
dob:new Date(Date.now())
})
Out put:
{
_id: ObjectId('678e6eb78024973ccf2e347f'),
rno: 6,
dob: 2025-01-20T15:41:43.926Z
}
>db.details.insert({
rno:7,
doj:Date()
})
Out put:
{
_id: ObjectId('678e6faa8024973ccf2e3480'),
rno: 7,
doj: 'Mon Jan 20 2025 21:15:46 GMT+0530 (India Standard Time)'
}

// trying to insert data with duplicate _id, it will not accept as _id is
primary key field

>db.details.insert({_id:ObjectId('678e6faa8024973ccf2e3480'),rno:5,nam
e:"Reena"})
MongoBulkWriteError:E11000duplicate key error collection:
details.detailsindex:_id_dupkey:{_id:ObjectId('678e6faa8024973ccf2e34
80') }

//Insert multiple documents at once


>db.details.insert([{rno:9,name:'Kavya'},{rno:10,name:'Kishore'},{rno:1
1,name:'Bindhu'}])

// to insert multiple values for one key using []

>db.details.insert({rno:12,name:'Ankit',hobbies:['singing','cricket','swimm
ing',],age:21})

Out put:

{
_id: ObjectId('678e72bf8024973ccf2e3485'),
rno: 12,
name: 'Ankit',
hobbies: [
'singing',
'cricket',
'swimming'
],
age: 21
}

Query Operation:
Use the find() method to query documents from a collection.
Syntax:
db.collection.find({ field: value })

>db.details.find({name: 'Ankit'})

Out Put:
{
_id: ObjectId('678e72bf8024973ccf2e3485'),
rno: 12,
name: 'Ankit',
hobbies: [
'singing',
'cricket',
'swimming'
],
age: 21}
Update Operation:
Use the updateOne() method to update a single document in a collection.
Syntax:
db.collection.updateOne( { field: value }, { $set: { fieldToUpdate:
newValue } })

>db.details.updateOne({age:21},{$set:{age:24}})

Out Put:
{
_id: ObjectId('678e72bf8024973ccf2e3485'),
rno: 12,
name: 'Ankit',
hobbies: [
'singing',
'cricket',
'swimming'
],
age: 25
}

Delete Operation:
Use the deleteOne() method to delete a single document from a
collection.
Syntax:
db.collection.deleteOne({ field: value })

>db.details.deleteOne({age:25})

//It will remove record having rno as 4

> db. details.remove({rno:4})

//It will remove only one record having rno as 4

> db. details.remove({rno:4},1)

//It will remove all records


>db. details.remove({})
>db. details.deleteMany({})
>db. details.deleteMany( { location: "chennai" } )
>db. details.deleteOne( { location: "chennai" } )
Projection Operation:
Use the second parameter of the find() method to specify which fields
toinclude or exclude in the query result.
Syntax:
db.collection.find({}, { field1: 1, field2: 1, _id: 0 })
// Find command to show only names without condition
> db. details.find({},{name:1,_id:0})
{ "name" : "Ashiti" }
{ "name" : "Savita" }

Program 2

a.Develop a MongoDB query to select certain fields and ignore some


fields of the documentsfrom any collection.
Syntax:
db.collection.find({}, { field1: 1, field2: 1, _id: 0 })

>db.details.find({}, { rno: 1, name: 1, _id: 0 })

Out Put:
{
rno: 1,
name: 'Bhavana'
}
{
rno: 2,
name: 'Amith'
}
{
rno: 3,
name: 'Sagar'
}

db.collection.find({}) is used to retrieve all documents from the


collection.

>db.deatils.find({})

Out Put:
{
_id: ObjectId('678e50018024973ccf2e3479'),
rno: 1,
name: 'Bhavana',
email: 'bhavana@123',
location: 'delhi',
marks: 80
}
{
_id: ObjectId('678e51168024973ccf2e347a'),
rno: 2,
name: 'Amith',
email: 'Amith@123',
location: 'Pune',
marks: 90
}
{
_id: ObjectId('678e51278024973ccf2e347b'),
rno: 3,
name: 'Sagar',
email: 'sagar@123',
location: 'Chennai',
marks: 70
}

//{ field1: 1, field2: 1, _id: 0 } specifies the projection document where:

//field1: 1 and field2: 1 indicates that these fields will be included in the
result.

// _id: 0 indicates that the _id field will be excluded from the result.

//Find command with condition with giving name field only to show
>db.details.find({rno:3},{name:1})

Out Put:
{
name: 'Sagar'
}

//Find command with condition with giving name field only to show
and _id to hide
> db. details.find({rno:2},{name:1,_id:0})
Out Put:
{
name: 'Amith'
}

// Find command to show only names without condition


> db. details.find({},{name:1,_id:0})

Out Put:
{
name: 'Bhavana'
}
{
name: 'Amith'
}

{
name: 'Sagar'
}

b.Develop a MongoDB query to display the first 5 documents from


the results obtained in a.[use of limit and find]Limit Operation
:Used to restrict the number of documents returned by a query. This is
particularlyuseful when you're dealing with large datasets and you only
need a subset of documents.
Syntax:
db.collection.find({}, { field1: 1, field2: 1, _id: 0 }).limit(5)

>db.details.find({},{rno:1,name:1,_id:0}).limit(5)

Limit (5) limits the number of documents returned to 5

//Limit use to show only some records from starting- following


command shows only first 2records from collection

>db.details.find().limit(2)

Out Put:
{
_id: ObjectId('678e50018024973ccf2e3479'),
rno: 1,
name: 'Bhavana',
email: 'bhavana@123',
location: 'delhi',
marks: 80
}
{
_id: ObjectId('678e51168024973ccf2e347a'),
rno: 2,
name: 'Amith',
email: 'Amith@123',
location: 'Pune',
marks: 90
}
Program 3

a.Execute query selectors (comparison selectors, logical selectors)


and list out the results onany collection.

Comparison Selectors:
Comparison selectors are used to compare fields against specific values
orother fields. Here are some common comparison selectors:
$eq - Matches values that are equal to a specified value.
$ne- Matches all values that are not equal to a specified value.
$gt - Matches values that are greater than a specified value.
$gte- Matches values that are greater than or equal to a specified value.
$lt - Matches values that are less than a specified value.
$lte - Matches values that are less than or equal to a specified value.
$in- Matches any of the values specified in an array.
$nin- Matches none of the values specified in an array.

Logical Selectors:
Logical selectors are used to combine multiple conditions in a query.
Here aresome common logical selectors:
$and- Joins query clauses with a logical AND and requires that all
conditions be true.
$or- Joins query clauses with a logical OR and requires that at least one
condition be true.
$not - Inverts the effect of a query expression and returns documents that
do not match the queryexpression.
$nor - Joins query clauses with a logical NOR and requires that none of
the conditions be true.
>db.emp.insertMany([
{name:'Rohith',age:30,department:'HR',salary:50000)},
{name:'Sharath',age:24,department:'Engineering',salary:70000},
{name:'Sandya',age:29,department:'Engineering',salary:75000},
{name:'Nandini',age:35,department:'Marketing',salary:60000},
{name:'Ashwin',age:28,department:'Finance',salary:70000}
])

1.$eq (equal)
>db.emp.find({department:{$eq:'Engineering' }})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cee'),
name: 'Sharath',
age: 24,
department: 'Engineering',
salary: 70000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cef'),
name: 'Sandya',
age: 29,
department: 'Engineering',
salary: 75000
}

2.$ne(Not Equal)
>db.emp.find({department:{$ne: 'HR'}})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cee'),
name: 'Sharath',
age: 24,
department: 'Engineering',
salary: 70000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cef'),
name: 'Sandya',
age: 29,
department: 'Engineering',
salary: 75000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf0'),
name: 'Nandini',
age: 35,
department: 'Marketing',
salary: 60000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf1'),
name: 'Ashwin',
age: 28,
department: 'Finance',
salary: 70000
}

3.$gt(Greater Than)
>db.emp.find({age:{$gt:30}})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cf0'),
name: 'Nandini',
age: 35,
department: 'Marketing',
salary: 60000
}

4.$lt (Less Than)


>db.emp.find({salary:{$lt:70000}})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9ced'),
name: 'Rohith',
age: 30,
department: 'HR',
salary: 50000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf0'),
name: 'Nandini',
age: 35,
department: 'Marketing',
salary: 60000
}

5.$lte (Less Than or Equal)


>db.emp.find({age:{$lte:28}})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cee'),
name: 'Sharath',
age: 24,
department: 'Engineering',
salary: 70000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf1'),
name: 'Ashwin',
age: 28,
department: 'Finance',
salary: 70000
}

6.$and (Logical AND)


>db.emp.find({
$and:[
{department: 'Engineering'},
{salary:{$gt:70000}}
]
})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cef'),
name: 'Sandya',
age: 29,
department: 'Engineering',
salary: 75000
}
7.$or (Logical OR)
>db.emp.find({
$or:[
{department:'HR'},
{salary:{$lt:60000}}
]})
Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9ced'),
name: 'Rohith',
age: 30,
department: 'HR',
salary: 50000
}

8.$not (Logical NOT)


>db.emp.find({
Department:{
$not:{$eq:'Engineering'}
}
})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9ced'),
name: 'Rohith',
age: 30,
department: 'HR',
salary: 50000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf0'),
name: 'Nandini',
age: 35,
department: 'Marketing',
salary: 60000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf1'),
name: 'Ashwin',
age: 28,
department: 'Finance',
salary: 70000
}

9.$nor (Logical NOR)


>db.emp.find({
$nor:[
{department:'HR'},
{salary:{$gt:75000}}
]
})

Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cee'),
name: 'Sharath',
age: 24,
department: 'Engineering',
salary: 70000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cef'),
name: 'Sandya',
age: 29,
department: 'Engineering',
salary: 75000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf0'),
name: 'Nandini',
age: 35,
department: 'Marketing',
salary: 60000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf1'),
name: 'Ashwin',
age: 28,
department: 'Finance',
salary: 70000
}
b.Execute query selectors (Geospatial selectors, Bitwise selectors) and
list out the results onany collection.
Geospatial Selectors:

>db.Places.insertMany([
{ name: "Central Park", location: { type: "Point", coordinates: [-73.9654,
40.7829] } },
{ name: "Times Square", location: { type: "Point", coordinates: [-
73.9851, 40.7580] } },
{ name: "Brooklyn Bridge", location: { type: "Point", coordinates: [-
73.9969, 40.7061] } },
{ name: "Empire State Building", location: { type: "Point", coordinates: [-
73.9857, 40.7488] } },
{ name: "Statue of Liberty", location: { type: "Point", coordinates: [-
74.0445, 40.6892] } }
])

1.$near (Find places near a certain point)


//create index
>db.Places.createIndex({ location: "2dsphere" })
>db.Places.find({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9851, 40.7580]
},
$maxDistance: 5000 // distance in meters
}
}
})

Out Put:
{
_id: ObjectId('678f3ba3f79934df0e238cb7'),
name: 'Times Square',
location: {
type: 'Point',
coordinates: [
-73.9851,
40.758
]
}
}
{
_id: ObjectId('678f3ba3f79934df0e238cb9'),
name: 'Empire State Building',
location: {
type: 'Point',
coordinates: [
-73.9857,
40.7488
]
}
}
{
_id: ObjectId('678f3ba3f79934df0e238cb6'),
name: 'Central Park',
location: {
type: 'Point',
coordinates: [
-73.9654,
40.7829
]
}
}
2.$geoWithin (Find places within specific area)
>db.Places.find({
location: {
$geoWithin: {
$geometry: {
type: "Polygon",
coordinates: [
[
[-70.016, 35.715],
[-74.014, 40.717],
[-73.990, 40.730],
[-73.990, 40.715],
[-70.016, 35.715]
]
]
}
}
}
})

Out Put:
{
_id: ObjectId('678f3ba3f79934df0e238cb8'),
name: 'Brooklyn Bridge',
location: {
type: 'Point',
coordinates: [
-73.9969,
40.7061
]
}
}

Bitwise Selectors:
MongoDB does not directly support bitwise operators for querying.
However, you can still implement bitwise operations in your application
code to filter documents based on bitwise properties.

//Create the Devices Collection and Insert Documents

>db.Devices.insertMany([
{ name: "Device A", status: 5 }, // Binary: 0101
{ name: "Device B", status: 3 }, // Binary: 0011
{ name: "Device C", status: 12 }, // Binary: 1100
{ name: "Device D", status: 10 }, // Binary: 1010
{ name: "Device E", status: 7 } // Binary: 0111
])

1.$bitsAllSet (Find documents where all bits are set)


//Find devices where the binary status has both the 1st and 3rd bits set
(binary mask 0101, or decimal 5).
>db.Devices.find({
status: { $bitsAllSet: [0, 2] }
})

Out Put:
{
_id: ObjectId('6653703d4e38f292e52202d8'),
name: 'Device A',
status: 5
},
{
_id: ObjectId('6653703d4e38f292e52202dc'),
name: 'Device E',
status: 7
}

2. $bitsAnySet (Find documents where any of the bits are set)


//Find devices where the binary status has at least the 2nd bit set (binary
mask 0010, or decimal 2).
>db.Devices.find({
status: { $bitsAnySet: [1] }
})

Out Put:
{
_id: ObjectId('6653703d4e38f292e52202d9'),
name: 'Device B',
status: 3
},
{
_id: ObjectId('6653703d4e38f292e52202db'),
name: 'Device D',
status: 10
},
{
_id: ObjectId('6653703d4e38f292e52202dc'),
name: 'Device E',
status: 7
}

3. $bitsAllClear (Find documents where all bits are clear)


//Find devices where the binary status has both the 2nd and 4th bits clear
(binary mask 1010, or decimal 10).
>db.Devices.find({
status: { $bitsAllClear: [1, 3] }
})

Out Put:
{
_id: ObjectId('6653703d4e38f292e52202d8'),
name: 'Device A',
status: 5
}

4. $bitsAnyClear (Find documents where any of the bits are clear)


//Find devices where the binary status has at least the 1st bit clear (binary
mask 0001, or decimal 1).
>db.Devices.find({
status: { $bitsAnyClear: [0] }
})

Out Put:
{
_id: ObjectId('6653703d4e38f292e52202da'),
name: 'Device C',
status: 12
},
{
_id: ObjectId('6653703d4e38f292e52202db'),
name: 'Device D',
status: 10
}

Program 4
Create and demonstrate how projection operators ($, $elematch and
$slice) would be used in the MongoDB.
1. The $ Projection Operator
The $ operator is used to project the first matching element from an array
of embedded documents.
Example: Find the product named “Laptop” and project the review from
the user “Alice”.
>db.products.find(
{ name: "Laptop", "reviews.user": "Alice" },
{ "reviews.$": 1 }
)

Out Put:
{
_id: ObjectId('6790f7d904871f2f43db7634'),
reviews: [
{
user: 'Alice',
rating: 5,
comment: 'Excellent!'
}
]
}

2. The $elemMatch Projection Operator


The $elemMatch operator is used to project the first matching element
from an array based on specified criteria.
Example: Find the product named “Laptop” and project the review
where the rating is greater than 4.
>db.Products.find(
{ name: "Laptop" },
{ reviews: { $elemMatch: { rating: { $gt: 4 } } } }
)

Out Put:
{
_id: ObjectId('6790f80204871f2f43db7636'),
reviews: [
{
user: 'Alice',
rating: 5,
comment: 'Excellent!'
}
]
}

3. The $slice Projection Operator


The $slice operator is used to include a subset of the array field.
Example: Find the product named “Smartphone” and project the first
review.
>db.products.find(
{ name: "Smartphone" },
{ reviews: { $slice: 1 } }
)

Out Put:
{
_id: ObjectId('6790f80204871f2f43db7637'),
name: 'Smartphone',
brand: 'BrandB',
features: [
{
name: 'Processor',
value: 'Snapdragon 888'
},
{
name: 'RAM',
value: '8GB'
},
{
name: 'Storage',
value: '256GB'
}
],
reviews: [
{
user: 'Dave',
rating: 4,
comment: 'Good phone'
}
]
}

Program 5
Execute Aggregation operations ($avg, $min,$max, $push,
$addToSet etc.). students encourage to execute several queries to
demonstrate various aggregation operators).
To demonstrate aggregation operations such as $avg, $min, $max, $push,
and $addToSet in MongoDB, we will use a Sales collection. This
collection will contain documents representing sales transactions.

//First, we’ll create the Sales collection and insert sample documents.
db.Sales.insertMany([
{ date: new Date("2024-01-01"), product: "Laptop", price: 1200,
quantity: 1, customer: "Amar" },
{ date: new Date("2024-01-02"), product: "Laptop", price: 1200,
quantity: 2, customer: "Babu" },
{ date: new Date("2024-01-03"), product: "Mouse", price: 25, quantity: 5,
customer: "Chandra" },
{ date: new Date("2024-01-04"), product: "Keyboard", price: 45,
quantity: 3, customer: "Amar" },
{ date: new Date("2024-01-05"), product: "Monitor", price: 300, quantity:
1, customer: "Babu" },
{ date: new Date("2024-01-06"), product: "Laptop", price: 1200,
quantity: 1, customer: "Deva" }
])

1. $avg (Average)
//Calculate the average price of each product.
>>db.Sales.aggregate([
{
$group: {
_id: "$product",
averagePrice: { $avg: "$price" }
}
}
])

Out Put:
{
_id: 'Keyboard',
averagePrice: 45
}
{
_id: 'Laptop',
averagePrice: 1200
}
{
_id: 'Monitor',
averagePrice: 300
}
{
_id: 'Mouse',
averagePrice: 25
}
2. $min (Minimum)
Find the minimum price of each product.
>db.Sales.aggregate([
{
$group: {
_id: "$product",
minPrice: { $min: "$price" }
}
}
])

Out Put:
{
_id: 'Mouse',
minPrice: 25
}
{
_id: 'Laptop',
minPrice: 1200
}
{
_id: 'Keyboard',
minPrice: 45
}
{
_id: 'Monitor',
minPrice: 300
}

3. $max (Maximum)
Find the maximum price of each product.
>db.Sales.aggregate([
{
$group: {
_id: "$product",
maxPrice: { $max: "$price" }
}
}
])

Out Put:
{
_id: 'Mouse',
maxPrice: 25
}
{
_id: 'Keyboard',
maxPrice: 45
}
{
_id: 'Laptop',
maxPrice: 1200
}
{
_id: 'Monitor',
maxPrice: 300
}

4. $push (Push Values to an Array)


Group sales by customer and push each purchased product into an array.
>db.Sales.aggregate([
{
$group: {
_id: "$customer",
products: { $push: "$product" }
}
}
])

Out Put:
{
_id: 'Amar',
products: [
'Laptop',
'Keyboard'
]
}
{
_id: 'Babu',
products: [
'Laptop',
'Monitor'
]
}
{
_id: 'Chandra',
products: [
'Mouse'
]
}
{
_id: 'Deva',
products: [
'Laptop'
]
}

5. $addToSet (Add Unique Values to an Array)


Group sales by customer and add each unique purchased product to an
array.
>db.Sales.aggregate([
{
$group: {
_id: "$customer",
uniqueProducts: { $addToSet: "$product" }
}
}
])

Out Put:
{
_id: 'Amar',
uniqueProducts: [
'Laptop',
'Keyboard'
]
}
{
_id: 'Babu',
uniqueProducts: [
'Monitor',
'Laptop'
]
}
{
_id: 'Chandra',
uniqueProducts: [
'Mouse'
]
}
{
_id: 'Chandra',
uniqueProducts: [
'Mouse'
]}
Combining Aggregation Operations
Let’s combine several aggregation operations to get a comprehensive
report.
Example: Calculate the total quantity and total sales amount for each
product, and list all customers who purchased each product.

>db.Sales.aggregate([
{
$group: {
_id: "$product",
totalQuantity: { $sum: "$quantity" },
totalSales: { $sum: { $multiply: ["$price", "$quantity"] } },
customers: { $addToSet: "$customer" }
}
}
])

Out Put:
{
_id: 'Keyboard',
totalQuantity: 3,
totalSales: 135,
customers: [
'Amar'
]
}
{
_id: 'Monitor',
totalQuantity: 1,
totalSales: 300,
customers: [
'Babu'
]
}
{
_id: 'Mouse',
totalQuantity: 5,
totalSales: 125,
customers: [
'Chandra'
]
}
{
_id: 'Laptop',
totalQuantity: 4,
totalSales: 4800,
customers: [
'Amar',
'Babu',
'Deva'
]
}

Program 6
Execute Aggregation Pipeline and its operations (pipeline must
contain $match, $group, $sort, $project,
$skip etc. students encourage to execute several queries to
demonstrate various aggregation operators)
Let’s consider a scenario involving a restaurantDB database with
a restaurants collection. Each document in the restaurants collection
contains details about a restaurant, including its name, cuisine, location,
and an array of reviews. Each review includes a rating and a comment.
After creating the restaurantDB database and insert sample documents
into the restaurants collection we will create an aggregation pipeline as
shown below.

// Insert sample documents into the restaurants collection


>db.restaurants.insertMany([
{
name: "Biryani House",
cuisine: "Indian",
location: "Jayanagar",
reviews: [
{ user: "Aarav", rating: 5, comment: "Amazing biryani!" },
{ user: "Bhavana", rating: 4, comment: "Great place!" }
]
},
{
name: "Burger Joint",
cuisine: "American",
location: "Koramangala",
reviews: [
{ user: "Chirag", rating: 3, comment: "Average burger" },
{ user: "Devika", rating: 4, comment: "Good value" }
]
},
{
name: "Pasta House",
cuisine: "Italian",
location: "Rajajinagar",
reviews: [
{ user: "Esha", rating: 5, comment: "Delicious pasta!" },
{ user: "Farhan", rating: 4, comment: "Nice ambiance" }
]
},
{
name: "Curry Palace",
cuisine: "Indian",
location: "Jayanagar",
reviews: [
{ user: "Gaurav", rating: 4, comment: "Spicy and tasty!" },
{ user: "Harini", rating: 5, comment: "Best curry in town!" }
]
},
{
name: "Taco Stand",
cuisine: "Mexican",
location: "Jayanagar",
reviews: [
{ user: "Ishaan", rating: 5, comment: "Fantastic tacos!" },
{ user: "Jaya", rating: 4, comment: "Very authentic" }
]
}
])

// Run the aggregation pipeline query to display reviews summary


>db.restaurants.aggregate([
{
$match: {
location: "Jayanagar"
}
},
{
$unwind: "$reviews"
},
{
$group: {
_id: "$name",
averageRating: { $avg: "$reviews.rating" },
totalReviews: { $sum: 1 }
}
},
{
$sort: {
averageRating: -1
}
},
{
$project: {
_id: 0,
restaurant: "$_id",
averageRating: 1,
totalReviews: 1
}
},
{
$skip: 1
}
])

Out Put:
{
averageRating: 4.5,
totalReviews: 2,
restaurant: 'Curry Palace'
}
{
averageRating: 4.5,
totalReviews: 2,
restaurant: 'Taco Stand'
}

Aggregation Pipeline Explanation


1. $match: Filter restaurants by cuisine ("Jayanagar" location).
2. $unwind: Deconstruct the reviews array from each document to
output a document for each review.
3. $group: Group the documents by restaurant name and calculate the
average rating and total number of reviews.
4. $sort: Sort the results by average rating in descending order.
5. $project: Restructure the output to include only the restaurant
name, average rating, and total reviews.
6. $skip: Skip the first document.

Program 7

a. Find all listings with listing_url, name, address, host_picture_url in


the listings And Reviews collection that have a host with a picture
url.
To find all listings with listing_url, name, address,
and host_picture_url in the listingsAndReviews collection where the host
has a picture URL, let is create appropriate databases and queries as
follows.

Create the Database


First, switch to or create the database you want to use. For this example,
let’s call the database vacationRentals.

Create the listingsAndReviews Collection and Insert Documents


Next, create the listingsAndReviews collection and insert sample
documents. Here are a few example documents to illustrate the structure:

>db.listingsAndReviews.insertMany([
{
listing_url: "http://www.example.com/listing/123456",
name: "Beautiful Apartment",
address: {
street: "123 Main Street",
suburb: "Central",
city: "Metropolis",
country: "Wonderland"
},
host: {
name: "Alice",
picture_url: "http://www.example.com/images/host/host123.jpg"
}
},
{
listing_url: "http://www.example.com/listing/654321",
name: "Cozy Cottage",
address: {
street: "456 Another St",
suburb: "North",
city: "Smallville",
country: "Wonderland"
},
host: {
name: "Bob",
picture_url: ""
}
},
{
listing_url: "http://www.example.com/listing/789012",
name: "Modern Condo",
address: {
street: "789 Side Road",
suburb: "East",
city: "Gotham",
country: "Wonderland"
},
host: {
name: "Charlie",
picture_url: "http://www.example.com/images/host/host789.jpg"
}
}
])

Query to Find Listings with Host Picture URLs:


Now that the collection is set up, you can run the query to find all listings
with listing_url, name, address, and host_picture_url where the host
has a picture URL.
>db.listingsAndReviews.find(
{
"host.picture_url": { $exists: true, $ne: "" }
},
{
listing_url: 1,
name: 1,
address: 1,
"host.picture_url": 1
}
)
Out Put:

{
_id: ObjectId('6791fbc92a8f7e53e4316ea9'),
listing_url: 'http://www.example.com/listing/123456',
name: 'Beautiful Apartment',
address: {
street: '123 Main Street',
suburb: 'Central',
city: 'Metropolis',
country: 'Wonderland'
},
host: {
picture_url: 'http://www.example.com/images/host/host123.jpg'
}
}
{
_id: ObjectId('6791fbc92a8f7e53e4316eab'),
listing_url: 'http://www.example.com/listing/789012',
name: 'Modern Condo',
address: {
street: '789 Side Road',
suburb: 'East',
city: 'Gotham',
country: 'Wonderland'
},
host: {
picture_url: 'http://www.example.com/images/host/host789.jpg'
}
}

//Explanation:
 Query Filter:
 "host.picture_url": { $exists: true, $ne: "" }: This part of
the query ensures that only documents where
the host.picture_url field exists and is not an empty string are
selected.
 Projection:
 { listing_url: 1, name: 1, address: 1, "host.picture_url": 1
}: This part of the query specifies the fields to include in the
output. The 1 indicates that these fields should be included.
b. Using E-commerce collection write a query to display reviews
summary.
To display a summary of reviews in an e-commerce collection, we can
assume the ecommerce database contains a products collection with
documents structured to include reviews. Each product document could
have a reviews array with review details such as rating, comment, and
user.

// Insert sample documents into the products collection


>db.products.insertMany([
{
product_id: 1,
name: "Laptop",
category: "Electronics",
price: 1200,
reviews: [
{ user: "Alice", rating: 5, comment: "Excellent!" },
{ user: "Bob", rating: 4, comment: "Very good" },
{ user: "Charlie", rating: 3, comment: "Average" }
]
},
{
product_id: 2,
name: "Smartphone",
category: "Electronics",
price: 800,
reviews: [
{ user: "Dave", rating: 4, comment: "Good phone" },
{ user: "Eve", rating: 2, comment: "Not satisfied" },
{ user: "Frank", rating: 5, comment: "Amazing!" }
]
},
{
product_id: 3,
name: "Headphones",
category: "Accessories",
price: 150,
reviews: [
{ user: "Grace", rating: 5, comment: "Great sound" },
{ user: "Heidi", rating: 3, comment: "Okay" }
]
}
])
// Run the aggregation query to display reviews summary
>db.products.aggregate([
{
$unwind: "$reviews"
},
{
$group: {
_id: "$name",
totalReviews: { $sum: 1 },
averageRating: { $avg: "$reviews.rating" },
comments: { $push: "$reviews.comment" }
}
},
{
$project: {
_id: 0,
product: "$_id",
totalReviews: 1,
averageRating: 1,
comments: 1
}
}
])
Out Put:
{
totalReviews: 3,
averageRating: 4,
comments: [
'Excellent!',
'Very good',
'Average'
],
product: 'Laptop'
}
{
totalReviews: 2,
averageRating: 4,
comments: [
'Great sound',
'Okay'
],
product: 'Headphones'
}
{
totalReviews: 3,
averageRating: 3.6666666666666665,
comments: [
'Good phone',
'Not satisfied',
'Amazing!'
],
product: 'Smartphone'
}
//Explanation:
1. $unwind: Deconstructs the reviews array from each document to
output a document for each element.
2. $group: Groups the documents by product name, and calculates:
 totalReviews: The total number of reviews for each product.
 averageRating: The average rating of the reviews for each
product.
 comments: An array of all review comments for each product.
3. $project: Restructures the output documents to include the product
name, total reviews, average rating, and comments.

Program 8
a. Demonstrate creation of different types of indexes on collection
(unique, sparse, compound and multikey indexes).
First, let’s set up the restaurantDB database and insert sample documents
into the restaurants collection.

// Switch to the restaurantDB database


>use restaurantDB

// Insert sample documents into the restaurants collection


>db.restaurants.insertMany([
{
name: "Biryani House",
cuisine: "Indian",
location: "Downtown",
reviews: [
{ user: "Aarav", rating: 5, comment: "Amazing biryani!" },
{ user: "Bhavana", rating: 4, comment: "Great place!" }
],
contact: { phone: "1234567890", email: "[email protected]"
}
},
{
name: "Curry Palace",
cuisine: "Indian",
location: "Downtown",
reviews: [
{ user: "Gaurav", rating: 4, comment: "Spicy and tasty!" },
{ user: "Harini", rating: 5, comment: "Best curry in town!" }
],
contact: { phone: "0987654321", email: "[email protected]" }
},
{
name: "Taco Stand",
cuisine: "Mexican",
location: "Downtown",
reviews: [
{ user: "Ishaan", rating: 5, comment: "Fantastic tacos!" },
{ user: "Jaya", rating: 4, comment: "Very authentic" }
],
contact: { phone: "1122334455", email: "[email protected]" }
}
])

1. Unique Index
A unique index ensures that the indexed field does not contain duplicate
values.
>db.restaurants.createIndex({ "contact.email": 1 }, { unique: true })

2. Sparse Index
A sparse index only includes documents that contain the indexed field,
ignoring documents where the field is missing.
>db.restaurants.createIndex({ location: 1 }, { sparse: true })

3. Compound Index
A compound index indexes multiple fields within a single index.
>db.restaurants.createIndex({ name: 1, location: 1 })
4. Multikey Index
A multikey index is created on an array field, indexing each element of
the array.
>db.restaurants.createIndex({ reviews: 1 })
//verify the created indexes, you can use the getIndexes method.
>db.restaurants.getIndexes()

Out Put:
[
{ v: 2, key: { _id: 1 }, name: '_id_' },
{
v: 2,
key: { 'contact.email': 1 },
name: 'contact.email_1',
unique: true
},
{ v: 2, key: { location: 1 }, name: 'location_1', sparse: true },
{ v: 2, key: { reviews: 1 }, name: 'reviews_1' },
{ v: 2, key: { name: 1, location: 1 }, name: 'name_1_location_1' }
].

b. Demonstrate optimization of queries using indexes.


//find the data using indexes
>db.restaurants.find({name:"Biryani House"}).hint({"contact.email":1})

Out Put:
{
_id: ObjectId('6795d5281122406c5ec0f706'),
name: 'Biryani House',
cuisine: 'Indian',
location: 'Downtown',
reviews: [
{
user: 'Aarav',
rating: 5,
comment: 'Amazing biryani!'
},
{
user: 'Bhavana',
rating: 4,
comment: 'Great place!'
}
],
contact: {
phone: '1234567890',
email: '[email protected]'
}
}
//Explain query execution plan
>db. restaurants.find({cuisine: "Mexican"}).explain()

Out Put:
{
explainVersion: '1',
queryPlanner: {
namespace: 'restaurantDB.restaurants',
parsedQuery: {
cuisine: {
'$eq': 'Mexican'
}
},
indexFilterSet: false,
planCacheShapeHash: '98FD4995',
planCacheKey: '1DC1C771',
optimizationTimeMillis: 0,
maxIndexedOrSolutionsReached: false,
maxIndexedAndSolutionsReached: false,
maxScansToExplodeReached: false,
prunedSimilarIndexes: false,
winningPlan: {
isCached: false,
stage: 'COLLSCAN',
filter: {
cuisine: {
'$eq': 'Mexican'
}
},
direction: 'forward'
},
rejectedPlans: []
},
queryShapeHash:
'28643C5D1F922C5ECD8CD54ECEC0C1471354CB53EFB3BB1A0D7
DB1920123F1E6',
command: {
find: 'restaurants',
filter: {
cuisine: 'Mexican'
},
'$db': 'restaurantsDB'
},
serverInfo: {
host: 'DESKTOP-HUDPB77',
port: 27017,
version: '8.0.4',
gitVersion: 'bc35ab4305d9920d9d0491c1c9ef9b72383d31f9'
},
serverParameters: {
internalQueryFacetBufferSizeBytes: 104857600,
internalQueryFacetMaxOutputDocSizeBytes: 104857600,
internalLookupStageIntermediateDocumentMaxSizeBytes: 104857600,
internalDocumentSourceGroupMaxMemoryBytes: 104857600,
internalQueryMaxBlockingSortMemoryUsageBytes: 104857600,
internalQueryProhibitBlockingMergeOnMongoS: 0,
internalQueryMaxAddToSetBytes: 104857600,
internalDocumentSourceSetWindowFieldsMaxMemoryBytes:
104857600,
internalQueryFrameworkControl: 'trySbeRestricted',
internalQueryPlannerIgnoreIndexWithCollationForRegex: 1
},
ok: 1
}

Program 9
a. Develop a query to demonstrate Text search using catalog data
collection for a given word.
To demonstrate text search in MongoDB using a catalog collection, we’ll
follow these steps:
1. Create the catalog collection and insert sample documents.
2. Create a text index on the relevant fields.
3. Perform a text search query to find documents containing a specific
word.
For this example let us consider a movie database that has been imported
from a CSV file. We can import data from the CSV file using
the mongoimport utility as follows:
//Steps to import CSV file

Step1:Create Kannada Movies Data Base

Step2:CreateCatalog collection
Step3:click on import data button
Step4:select csv file click on import.

>db.catalog.countDocuments()

// Create a text index on the name and genre fields


>db.catalog.createIndex({name: "text", action: "text"})

//Perform a text search query to find documents containing the word


"maga"
>db.catalog.find({$text: {$search: "maga"}})

Out Put:
{
_id: ObjectId('6795ea9482ec11d124fdca30'),
name: 'Jayammana Maga',
year: 2013,
time: '139 min',
ratings: 7.1,
action: 'Drama ',
lang: 'kannada'
}
{
_id: ObjectId('6795ea9482ec11d124fdc967'),
name: 'Rajannana Maga',
year: 2018,
time: '143 min',
ratings: 7.8,
action: 'Action ',
lang: 'kannada'
}
{
_id: ObjectId('6795ea9482ec11d124fdcbd8'),
name: 'Thayigethakkamaga',
year: 2018,
time: '147 min',
ratings: 5.4,
action: 'Drama ',
lang: 'kannada'
}
{
_id: ObjectId('6795ea9482ec11d124fdca84'),
name: 'Bhootayyana Maga Ayyu',
year: 1974,
time: '155 min',
ratings: 8.3,
action: 'Drama ',
lang: 'kannada'
}
{
_id: ObjectId('6795ea9482ec11d124fdca1d'),
name: 'Jaga Mechida Maga',
year: 1972,
time: '153 min',
ratings: 8.2,
action: 'Drama ',
lang: 'kannada'
}
{
_id: ObjectId('6795ea9482ec11d124fdc9ff'),
name: 'Daari Tappida Maga',
year: 1975,
time: '138 min',
ratings: 7.6,
action: 'Crime, Drama ',
lang: 'kannada'
}

b. Develop queries to illustrate excluding documents with certain


words and phrases .
Suppose we want to list movies that belong to crime or romance (or
both) genre but not belonging to the action genre. Since this will yield
too many results we will restrict the search to the year 2021.
>db.catalog.createIndex({ name: "text",action: "text" })
>db.catalog.find({ $text: { $search: "crime romance -action" }, year:2021
})

Out Put:
{
_id: ObjectId('6795eeff82ec11d124fdcf1e'),
name: 'RakthaGulabi',
year: 2021,
time: '132 min',
ratings: 9.4,
action: 'Crime ',
lang: 'kannada'
}
{
_id: ObjectId('6795eeff82ec11d124fdcff9'),
name: 'Laddu',
year: 2021,
time: '127 min',
ratings: 8.6,
action: 'Comedy, Romance ',
lang: 'kannada'
}

Program 10
Develop an aggregation pipeline to illustrate Text search on Catalog
data collection.
The aggregation framework in MongoDB is a powerful tool for data
processing and transformation. It consists of a series of stages, each stage
performing an operation on the input documents and passing the results to
the next stage. This sequence of operations is called an aggregation
pipeline.
Here is a step-by-step guide to using the aggregation pipeline in
MongoDB,
withexamplesofvariousstagessuchas $match, $group, $sort, $project, $s
kip, and others.

Example Aggregation Pipeline


Let’s create an aggregation pipeline that includes various stages:
1. $match: Filter documents to include only those in the year 2017.
2. $group: Group documents by genre and calculate the average
rating for each genre.
3. $sort: Sort the results by avgRating in descending order.
4. $project: Include specific fields in the output
5. $limit: Limit the output to 5 results.
6. $skip: Skip the first two results.
>result = db.catalog.aggregate([

// 1. Match stage: Filter documents by year 2017

{$match:{year :2017}},

// 2. Group stage: Group by genre and calculate average rating


{$group:{_id: "$action", avgRating:{$avg: "$ratings"}}},

// 3. Sort stage: Sort by avgRating in descending order

{$sort: {avgRating:-1}},

// 4. Project stage: Include specific fields

{$project:{year:"$year", avgRating:1, action:1} },

// 5. Limit stage: Limit the output to 5 results

{$limit:5} ]).toArray()
print("Top 5 rated movie genres with their average rating")
printjson(result)

Out Put:
Top 5 rated movie genres with their average rating
[
{ _id: 'Mystery ', avgRating: 7.9 },
{ _id: 'Comedy, Drama ', avgRating: 7.9 },
{ _id: 'Adventure, Family ', avgRating: 7.8 },
{ _id: 'Drama, Romance, Thriller ', avgRating: 7.7 },
{ _id: 'Drama ', avgRating: 7.616666666666667 }
]

Adding another stage using $skip


To find the remaining five genres among the top-rated seven genres after
skipping the first two, we can use the $skip stage in the aggregation
pipeline.

>result2 = db.catalog.aggregate([

// 1. Match stage: Filter documents by year 2017


{$match:{year :2017}},
// 2. Group stage: Group by genre and calculate average rating
{$group:{_id: "$action", avgRating:{$avg: "$ratings"}}},

// 3. Sort stage: Sort by avgRating in descending order


{$sort: {avgRating:-1}},
// 4. Project stage: Include specific fields
{$project:{year:"$year", avgRating:1, action:1} },

// 5. Limit stage: Limit the output to 7 results


{$limit:7},

// 6. Skip stage: Skip the first two results


{$skip:2} ]).toArray()

print("Top 7 rated movie genres with their average rating with the first
two skipped")
printjson(result2)

Out Put:
Top 7 rated movie genres with their average rating with the first two
skipped

[
{ _id: 'Adventure, Family ', avgRating: 7.8 },
{ _id: 'Drama, Romance, Thriller ', avgRating: 7.7 },
{ _id: 'Drama ', avgRating: 7.616666666666667 },
{ _id: 'Drama, History, Musical ', avgRating: 7.5 },
{ _id: 'Comedy, Drama, Family ', avgRating: 7.5 }
]

The aggregation pipeline in MongoDB provides a flexible and powerful


framework for data processing. By chaining multiple stages, you can
filter, group, sort, project, and transform your data to suit your specific
requirements.

You might also like