0% found this document useful (0 votes)
59 views33 pages

MongoDB Lab Manual

The document is a laboratory manual for a MongoDB course at BMS Institute of Technology and Management, aimed at 4th semester students in AI&ML and CSBS departments. It outlines course objectives, outcomes, assessment plans, and detailed experiments to be conducted, focusing on MongoDB operations such as data manipulation, indexing, and aggregation. The manual also includes suggested learning resources and evaluation criteria for practical assessments.

Uploaded by

Sahana Ks
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)
59 views33 pages

MongoDB Lab Manual

The document is a laboratory manual for a MongoDB course at BMS Institute of Technology and Management, aimed at 4th semester students in AI&ML and CSBS departments. It outlines course objectives, outcomes, assessment plans, and detailed experiments to be conducted, focusing on MongoDB operations such as data manipulation, indexing, and aggregation. The manual also includes suggested learning resources and evaluation criteria for practical assessments.

Uploaded by

Sahana Ks
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

BMS INSTITUTE OF TECHNOLOGY AND MANAGEMENT

(An Autonomous Institution, Affiliated to VTU, Belagavi)


Avalahalli, Doddaballapur Main Road, Bengaluru – 560119

LABORATORY MANUAL
mongoDB
(BAIL456B)

For 4th Semester - 2022 Scheme

Common to
Department of Artificial Intelligence and Machine Learning
&
Department of Computer Science and Business Systems

Prepared By
Prof. Yatheesh N G, Assistant Professor, AI&ML dept.
Prof. PradeepKumar G M, Assistant Professor, CSBS Dept.

Academic Year: 2024-25


COURSE LEARNING OBJECTIVES:
This course will enable students to

1. Understand basic MongoDB functions, operators and types of operations in MongoDB.

2. Demonstrate the use of Indexing, Advanced Indexing in MongoDB.

3. Apply the aggregation and Map Reduction in MongoDB.

4. Demonstrate text searching on collections in MongoDB.

Course Outcomes:

At the end of this course, students will be able to:


Execute basic MongoDB operations including data insertion, filtering, updating, deletion,
CO1 and field projection.

Apply advanced selectors and operators (comparison, logical, geospatial, bitwise,


CO2 projection) for data manipulation.

Perform data analysis using aggregation operators and multi-stage aggregation pipelines.
CO3
Use indexing techniques like unique, sparse, compound, and multikey indexes to optimize
CO4 query performance.

Develop complex queries for real-world applications involving text search, filtering, and
CO5 dataset summarization.
Assessment Plan
DEPARTMENT OF COMPUTER SCIENCE AND BUSINESS SYSTEMS
Choice Based Credit System (CBCS)
SEMESTER – IV
MongoDB ([Link]) 1
(Effective from the academic year 2023-2024)
Course Code BAIL456B CIE Marks 50
Teaching Hours/Week (L:T:P: S) [Link] SEE Marks 50
Credits 01 Exam Hours 03
Examination type (SEE) Practical
Course Objectives:
This course aims to prepare the students to:
● 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.
[Link] 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)
[Refer: Book 1 chapter 4].
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]
[Refer: Book1 Chapter 4, book 2: chapter 5]
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
[Refer: Book 3 Chapter 13]
4 Create and demonstrate how projection operators ($, $elematch and $slice) would be
used in the MongoDB.
[Refer: Book 3 Chapter 14]
5 Execute Aggregation operations ($avg, $min,$max, $push, $addToSet etc.). students
encourage to execute several queries to demonstrate various aggregation operators)
[Refer: Book 3 Chapter 15]
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)
[Refer book 2: chapter 6 ]
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.
[refer Book2: chapter 6]
8 a. Demonstrate creation of different types of indexes on collection (unique, sparse,
compound and multikey indexes)
b. Demonstrate optimization of queries using indexes.
[Refer: Book 2: Chapter 8 and Book 3: Chapter 12]
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
[Refer: Book 2: Chapter 9]
10 Develop an aggregation pipeline to illustrate Text search on Catalog data collection.
[Refer: Book 2 :Chapter 9]
Course outcomes :
At the end of the course the student will be able to:
CO1: Make use of MangoDB commands and queries.
CO2: Illustrate the role of aggregate pipelines to extract data.
CO3 Demonstrate optimization of queries by creating indexes.
CO4: Develop aggregate pipelines for text search in collections.
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
 BOOK 3: "MongoDB Complete Guide" by Manu Sharma 1st ed, bpb publication, 2023.
 instaIIation of MongoDB Video: [Link]
 video on Aggregation: [Link]
 MongoDB in action book Code downIoad URL: [Link]
 MongoDB Exercise UR

Assessment Details (both CIE and SEE)


Lab Evaluation Scheme
1. Ten marks for every experiment (10 X 10 = 100 marks), round it off to 30 marks.
2. Ten marks for every experiment will be evaluated for write-up, program execution, the
procedure followed while execution and viva voce after each exercise.
3. Internal practical test for 100 marks to be given and the marks scored will be scaled down to
20 marks.
4. A Minimum of 20 mark is to be scored in CIE.
5. SEE examination for the Lab is to be conducted for 100 marks and reduced to 50 marks.
6. A Minimum of 18 marks is to be scored in SEE.
Note: Open Ended experiment will be done by the students in the Lab session. A total mark
of 40 is to be scored by the student from both CIE and SEE together out of 100.
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 are
appointed by the Head of the Institute.
● The examination schedule and names of examiners are informed to the university before the
conduction of the examination. These practical examinations are to be conducted between the
schedule 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 script
to be strictly adhered to by the examiners. OR based on the course requirement evaluation
rubrics shall be decided jointly by examiners.
● Students can pick one question (experiment) from the questions lot prepared by the examiners
jointly.
● Evaluation of test write-up/ conduction procedure and result/viva will be conducted jointly by
examiners.
● General rubrics suggested for SEE are mentioned here, writeup-20%, Conduction procedure
and result in -60%, Viva-voce 20% of maximum marks. SEE for practical shall be evaluated for
100 marks and scored marks shall be scaled down to 50 marks (however, based on course
type, rubrics shall be decided 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 03 hours
Department of Computer Science and Business Systems

1 a. Illustration of Where Clause, AND, OR operations in MongoDB.

 Creating database
>use ProgrammingBooks

 create the collection inside the database


>[Link]("BookDetails")

 Inserting Documents into collection

Method 1: Insert the single value or document


>[Link]({
_id: 1,
title: "Clean Code",
author: "Robert C. Martin",
category: "Software Development",
year: 2008
})

Method 2: Insert multiples values or document in collection


>[Link]([
{_id: 2, title: "Clean Code", author: "Robert C. Martin", category: "Software
Development", year: 2008 },
{_id: 3, title: "JavaScript: The Good Parts", author: "Douglas Crockford",
category: "JavaScript", year: 2008 },
{_id: 4, title: "Design Patterns", author: "Erich Gamma", category: "Software
Design", year: 1994 },
{_id: 5, title: "Introduction to Algorithms", author: "Thomas H. Cormen",
category: "Algorithms", year: 2009 },
{_id: 6, title: "Python Crash Course", author: "Eric Matthes", category:
"Python", year: 2015 }
] );

 Displaying documents within the collection


> [Link]( )
Or
> [Link]( ).pretty( )

 Displaying documents based on condition/s(using $where)


>[Link]({ year: 2008 }).pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 1


Department of Computer Science and Business Systems

Or
> [Link]({ year:{$eq: 2008 }}).pretty( )
Or
> [Link]({$where:"[Link]==2008"}).pretty()

 Combining multiple conditions using $and and $or

Syntax: $and
{ $and: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

Example: [Link]({
$and: [
{ category: "Software Development" },
{ year: 2008 }
]
}).pretty()
Syntax: $or
{ $or: [ { <expression1> }, { <expression2> } , ... , { <expressionN> } ] }

Example:
[Link]({
$or: [
{ category: "JavaScript" },
{ year: 2015 }
]
}).pretty()

 Using $in for displaying documents


Syntax: { field: { $in: [<value1>, <value2>, ... <valueN> ] } }

Example: [Link]({category:{$in:['javascript','Software Development']}})


.pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 2


Department of Computer Science and Business Systems

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


Insert, Query, Update, Delete and Projection. (Note: use any collection)

 Retrieving documents based on different conditions using Comparison


operators

Examples:
>[Link]({ year: { $gt: 2000 } }).pretty( )
>[Link]({ year: { $gte: 2000 } }).pretty( )
>[Link]({ year: { $lt: 2000 } }).pretty( )
>[Link]({ year: { $lte: 2000 } }).pretty( )
>[Link]({ year: { $ne: 2000 } }).pretty( )
>[Link]({category:{$in:['javascript','Software Development']}}).pretty( )
>[Link]({category:{$nin:['javascript','Software Development']}}).pretty( )

Combining multiple conditions


>[Link]({$and:[{year:{$gt:2010}},{category:{$eq:'Java and J2EE'}}]})

 Updating the field/s of documents in the collection


Method 1: updating one document(using updateOne( ))

Syntax: [Link](
{filter},
{ $set: { field1: value1 }, $inc: { filed2: value2 } },
...
)
Where:
Filter: The selection criteria for the update. The same query selectors as in the find()
method are available.
Specify an empty document { } to update the first document returned in the collection.

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 3


Department of Computer Science and Business Systems

Example:
>[Link](
{ title: "Clean Code: A Handbook of Agile Software Craftsmanship" },
{ $set: { author: "vtucode" } }
)

Method 2: updating mutiple documents(using updateMany( ))


>[Link](
{ year: { $lt: 2010 } },
{ $set: { category: "vtucode website" } }
)

And execute the following command to see the updations


> [Link]({ year: { $lt: 2010 } }).pretty( )

Note: updateMany( ) can also be used to add the field to existing documents

Example: adding publisher field to all the documents


>[Link]({category:{$exists:true}},{$set:{pubisher:"McGrawHill"}})

Method 3: using findOneAndUpdate( )


Syntax:
[Link]( filter, update, options )

 returnDocument: "before" returns the original document.


 returnDocument: "after" returns the updated document

Example:
>[Link]({category:"Python"},
{$set:{title:"Python:Complete refrence"}},{returnDocumnet:"after"})

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 4


Department of Computer Science and Business Systems

Method 4: using findAndModify( )

This method can handle three types of operations:


i. Update: Modify the existing document.
>[Link]({query:{category:'Python'},
update:{$set:{title:"Python:For Begginers",year:2015}}})

>[Link]({query:{category:'Python
Programming'},update:{$set:{title:"Python:For Begginers",year:2015}},new:true})

ii. Remove: Delete the document.


>[Link]({
query: {category:'Python Programming'},
sort: { score: 1 },
remove: true
});

iii. Upsert: Insert a new document if no document matches the query.


>[Link] ({query:{category:"Java and J2EE"},
update:{$set:{title:"JAVA2: complete reference",year:2012}},
upsert:true,
new:true})

 Delete the documents


Method 1: Delete single value or document in collection
>[Link]({ _id: 2 })

Method 2: Delete multiple values or document in collection


>[Link]({ year: { $lt: 1995 } })

Method 3: Delete all documents


>[Link]({ })

 verify the deleted document


>[Link]().pretty( )
 Deleting all documents:
>[Link]({ })

Verify the details of the collections by executing the command:


>[Link]().pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 5


Department of Computer Science and Business Systems

 Projection Operations: To retrieve specific include field values or document in collection


By using 1 and 0 can retrieve the details of specific fields of the documents

>[Link]({ },{category:1,title:1,price:1}) //with _id filed by default

>[Link]({},{category:1,title:1,price:1,_id:0}) //exclude _id field


>[Link]({title:'Clean Code'},{category:1,title:1,price:1,_id:0}) //with condition

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


fields of the documents from any collection.
To retrieve specific include field values or document in collection
By using 1 and 0 can retrieve the details of specific fields of the documents
 Including Specific Fields:

>[Link]({ },{category:1,title:1,price:1}) //with _id filed by default


>[Link]({},{category:1,title:1,price:1,_id:0}) //exclude _id field

 Combining Filter and Projection:


>[Link]({title:'Clean Code'},{category:1,title:1,price:1,_id:0}) //with condition

 Excluding Specific Fields:

>[Link]({title:'Clean Code'},{category:0,_id:0}) //excluding multiple fields

b. Develop a MongoDB query to display the first 5 documents from the results
obtained.[use of limit and find]
>[Link]( ) //displays number of documents in the collection
>[Link]().limit(5) //displays first 5 documents
>[Link]({},{category:1,title:1,price:1,_id:0}).limit(5)

>[Link]().skip(2) //displays 3rd document onwards by skipping first 2

Sorting the documents using sort( )


>[Link]().skip(2).sort('category')
>[Link]().sort().limit(4)
>[Link]({},{title:1,author:1,year:1,_id:0}).sort().limit(4)
>[Link]({},{title:1,author:1,year:1,_id:0}).sort("year").limit(6)
>[Link]({},{title:1,author:1,year:1,_id:0}).sort({"year":-1}).limit(6)
>[Link]({},{title:1,author:1,year:1,_id:0}).sort("created_at",-1).limit(4)

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 6


Department of Computer Science and Business Systems

3 Execute query selectors (comparison selectors, logical selectors ) and list


out the results on any collection

 create the new database as well as switch the database


>use companyDB

 insert the multiple values or documents


>[Link]([
{ name: "Alice", age: 30, department: "HR", salary: 50000,
joinDate: new Date("2015-01-15") },
{ name: "Bob", age: 24, department: "Engineering", salary: 70000,
joinDate: new Date("2019-03-10") },
{ name: "Charlie", age: 29, department: "Engineering", salary: 75000,
joinDate: new Date("2017-06-23") },
{ name: "David", age: 35, department: "Marketing", salary: 60000,
joinDate: new Date("2014-11-01") },
{ name: "Eve", age: 28, department: "Finance", salary: 80000,
joinDate: new Date("2018-08-19") }
])

 comparison selectors:

Operator Description Example

$eq Equal to { age: { $eq: 25 } }

$ne Not equal to { status: { $ne: "A" } }

$gt Greater than { age: { $gt: 30 } }

$gte Greater than or equal to { age: { $gte: 18 } }

$lt Less than { age: { $lt: 60 } }


$lte Less than or equal to { age: { $lte: 40 } }
$in Value in an array { status: { $in: ["A", "B"] } }
$nin Value not in an array { status: { $nin: ["C"] } }

 $eq (Equal)
>[Link]({ department: { $eq: "Engineering" } }).pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 7


Department of Computer Science and Business Systems

 $ne (Not Equal)


>[Link]({ department: { $ne: "HR" } }).pretty( )

 $gt (Greater than)


>[Link]({ age: { $gt: 30 } }).pretty()
 $lt (less than)
>[Link]({ salary: { $lt: 70000 } }).pretty()
 $gte (Greater Than or Equal)
>[Link]({ joinDate: { $gte: new Date("2018-01-01") } }).pretty()
 $lte (Less Than or Equal)
>[Link]({ age: { $lte: 28 } }).pretty()

 logical selectors

Operator Description Example Use

$and Matches documents that match all conditions All must be true
$or Matches documents that match any condition At least one must be true
$not Inverts the result of a condition Opposite of the condition
$nor Matches documents that fail all conditions None should be true

 $and (Logical AND)


Example: Find employees who are in the “Engineering” department and have a salary greater
than 70000.
>[Link]({ $and: [ { department: "Engineering" }, { salary: { $gt: 70000 } } ]
}).pretty( )

 $or (Logical OR)


Example: Find employees who are either in the “HR” department or have a salary less than
60000.
>[Link]({ $or: [ { department: "HR" }, { salary: { $lt: 60000 } } ] }).pretty()

 $not (Logical NOT)


Example: Find employees who are not in the “Engineering” department.
>[Link]({ department: { $not: { $eq: "Engineering" } } }).pretty( )
 $nor (Logical NOR)

Example: Find employees who are neither in the “HR” department nor have a salary greater
than 75000.
>[Link]({ $nor: [ { department: "HR" }, { salary: { $gt: 75000 } } ] }).pretty()

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 8


Department of Computer Science and Business Systems

 Execute query selectors (Geospatial selectors, Bitwise selectors ) and list


out the results on any collection

 Geospatial selectors:
 Geospatial selectors in MongoDB are used to store and query geospatial data like
coordinates, areas, and distances.
 MongoDB supports 2D (flat plane) and 2dsphere (Earth-like) indexes, and has powerful
query operators for geospatial operations.
 To specify GeoJSON data, use an embedded document with:

a field named type that specifies the GeoJSON object type, and
a field named coordinates that specifies the object's coordinates.
<field>: { type: <GeoJSON type> , coordinates: <coordinates> }

 Create collection
>use geodatabase

 Insert the documents describing the places


>[Link]([
{ 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] } }
])

Note:
 Geospatial indexes in MongoDB are designed to efficiently perform spatial queries, like finding
locations near a specific point, within a given radius, or within a particular shape.
 They allow MongoDB to quickly filter and return documents based on their geographical
location without scanning the entire collection.

 Create a geospatial index


[Link]({ location: "2dsphere" })

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 9


Department of Computer Science and Business Systems

 $near (Find places near a certain point):


Example: Find places near a specific coordinate, for example, near Times Square.

[Link]({
location: {
$near: {
$geometry: {
type: "Point",
coordinates: [-73.9851, 40.7580]
},
$maxDistance: 5000 // distance in meters
}
}
}).pretty( )

 $geoWithin (Find places within a specific area):

Example: Find places within a specific polygon, for example, an area covering part of
Manhattan.

[Link]({
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]
]
]
}
}
}
}).pretty()

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 10


Department of Computer Science and Business Systems

 Bitwise selectors
 Bitwise selectors are query operators that allow you to perform bit-level queries on
integer fields.
 These selectors are useful when you store multiple Boolean flags or states in a single
integer field using bit masking.

Bit Position Meaning Binary Decimal

0 Is Active 0001 1
1 Is Manager 0010 2
2 Has Remote Access 0100 4
3 Is On Probation 1000 8

Example:
An employee with flags = 5 (binary 0101) means:
 Is Active ✅
 Is Manager ❌
 Has Remote Access ✅
 Is On Probation ❌

 Create database
>use empDB

 Create collection
>[Link](“employees”)

 Insert documents into the collection


>[Link]([
{ name: "Alice", flags: 1 }, // Active
{ name: "Bob", flags: 3 }, // Active + Manager
{ name: "Charlie", flags: 5 }, // Active + Remote Access
{ name: "David", flags: 10 }, // Manager + Probation
{ name: "Eve", flags: 15 } // All flags set
])

1. Get all active employees (bit 0 set)


[Link]({ flags: { $bitsAllSet: 1 } })

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 11


Department of Computer Science and Business Systems

2. Get employees who are either managers OR have remote access (bit 1 or 2 set)
[Link]({ flags: { $bitsAnySet: [1, 2] } })

3. Get employees who are not on probation (bit 3 is clear)


[Link]({ flags: { $bitsAllClear: 8 } })

4. Get employees who are active and managers (bit 0 and 1 set)
[Link]({ flags: { $bitsAllSet: [0, 1] } })

5. Get employees where any flag is clear (not all permissions)


[Link]({ flags: { $bitsAnyClear: [0, 1, 2, 3] } })

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

 Create database
>use retailDB
 Create collection
>[Link](‘Products’)

 Insert documents into the collection

[Link]([
{
name: "Laptop",
brand: "BrandA",
features: [
{ name: "Processor", value: "Intel i7" },
{ name: "RAM", value: "16GB" },
{ name: "Storage", value: "512GB SSD" }
],
reviews: [
{ user: "Alice", rating: 5, comment: "Excellent!" },
{ user: "Bob", rating: 4, comment: "Very good" },
{ user: "Charlie", rating: 3, comment: "Average" }
]
},

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 12


Department of Computer Science and Business Systems

{
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" },
{ user: "Eve", rating: 2, comment: "Not satisfied" }
]
}
])

Projection Operators:
1. The $ Projection Operator: 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”.
> [Link](
{ name: "Laptop", "[Link]": "Alice" },
{ "reviews.$": 1 }
).pretty( )

Using aggregate pipelining


>[Link]([
{$match:{$and:[{ name:{$eq:"Laptop"},"[Link]":{$eq:"Alice"}}] } },
{$project:{reviews:"$reviews"} }
]).pretty()

2. The $elemMatch Projection Operator: 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.
> [Link](
{ name: "Laptop" },
{ reviews: { $elemMatch: { rating: { $gt: 4 } } } }
).pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 13


Department of Computer Science and Business Systems

3. $slice Projection Operator: used to include a subset of the array field.

Example: Find the product named “Smartphone” and project the first review.

>[Link](
{ name: "Smartphone" },
{ reviews: { $slice: 1 } }
).pretty( )

Example with Multiple Projection Operators: Find the product named “Laptop” and project
the name, the first two features, and the review with the highest rating.

> [Link]( { name: "Laptop" },


{ name: 1,
features: { $slice: 2 },
reviews: { $elemMatch: { rating: 5 } } } ).pretty( )

Execute Aggregation operations ($avg, $min,$max, $push, $addToSet etc.). students


5 encourage to execute several queries to demonstrate various aggregation operators)

 Create database
> use salesDB
 Create collection
>[Link](‘Sales’)

> [Link]([
{ 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" }
])

Aggregation Operations:

1. $avg (Average): Calculate the average price of each product.


> [Link]([ { $group: { _id: "$product",
averagePrice: { $avg: "$price" } } } ]).pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 14


Department of Computer Science and Business Systems

2. $min (Minimum): Find the minimum price of each product.


> [Link]([ { $group: { _id: "$product",
minPrice: { $min: "$price" } } } ]).pretty()

3. $max (Maximum): Find the maximum price of each product.


> [Link]([ { $group: { _id: "$product",
maxPrice: { $max: "$price" } } } ]).pretty()

4. $push (Push Values to an Array): Group sales by customer and push each purchased product
into an array.
> [Link]([ { $group: { _id: "$customer",
products: { $push: "$product" } } } ]).pretty()

5. $addToSet (Add Unique Values to an Array): Group sales by customer and add each unique
purchased product to an array.
> [Link]([ { $group: { _id: "$customer",
uniqueProducts: { $addToSet: "$product" } } } ]).pretty()

Combining Aggregation Operations:

Example: Calculate the total quantity and total sales amount for each product, and list all
customers who purchased each product.

[Link]([
{
$group: {
_id: "$product",
totalQuantity: { $sum: "$quantity" },
totalSales: { $sum: { $multiply: ["$price", "$quantity"] } },
customers: { $addToSet: "$customer" }
}
}
]).pretty( )

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 15


Department of Computer Science and Business Systems

Execute Aggregation Pipeline and its operations (pipeline must contain $match, $group,
6 $sort, $project,$skip etc. students encourage to execute several queries to demonstrate
various aggregation operators)

 Create database
>use restaurantDB

 Create collection
>[Link](‘restaurants’)

 Insert documents
[Link]([
{
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" }
]
},

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 16


Department of Computer Science and Business Systems

{
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" }
]
}
])
Aggregation Pipeline and its operations:

 Execute Aggregation Pipeline and its operations (pipeline must contain match, group, sort,
project, $skip etc.)

[Link]([
{
$match: {
"location": "Jayanagar"
}
},
{
$unwind: "$reviews"
},
{
$group: {
_id: "$name",
averageRating: { $avg: "$[Link]" },
totalReviews: { $sum: 1 }
}
},

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 17


Department of Computer Science and Business Systems

{
$sort: {
averageRating: -1
}
},
{
$project: {
_id: 0,
restaurant: "$_id",
averageRating: 1,
totalReviews: 1
}
},
{
$skip: 1
}
]).pretty( )

Note: Execution of query


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.

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 18


Department of Computer Science and Business Systems

a. Find all listings with listing_url, name, address, host_picture_url in the listings And
7
Reviews collection that have a host with a picture url

 Create database
> use vacationRentals
 Create collection
>[Link](‘listingsAndReviews’)

 Insert documents

[Link]([
{
listing_url: "[Link]
name: "Beautiful Apartment",
address: {
street: "123 Main Street",
suburb: "Central",
city: "Metropolis",
country: "Wonderland"
},
host: {
name: "Alice",
picture_url: "[Link]
}
},
{
listing_url: "[Link]
name: "Cozy Cottage",
address: {
street: "456 Another St",
suburb: "North",
city: "Smallville",
country: "Wonderland"
},
host: {
name: "Bob",
picture_url: ""
}
},

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 19


Department of Computer Science and Business Systems

{
listing_url: "[Link]
name: "Modern Condo",
address: {
street: "789 Side Road",
suburb: "East",
city: "Gotham",
country: "Wonderland"
},
host: {
name: "Charlie",
picture_url: "[Link]
}
}
])

 Query to Find Listings with Host Picture URLs: (use $exists)


[Link](
{
"host.picture_url": { $exists: true, $ne: "" }
},
{
listing_url: 1,
name: 1,
address: 1,
"host.picture_url": 1
}
).pretty()

b. Using E-commerce collection write a query to display reviews summary.

 Create database
> use ecommerce

 Create collection
>[Link](‘products’)

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 20


Department of Computer Science and Business Systems

 Insert documents
[Link]([
{
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" }
]
}
])

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 21


Department of Computer Science and Business Systems

 Query to Find E-commerce collection:

Note: 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.

>[Link]([
{
$unwind: "$reviews"
},
{
$group: {
_id: "$name",
totalReviews: { $sum: 1 },
averageRating: { $avg: "$[Link]" },
comments: { $push: "$[Link]" }
}
},
{
$project: {
_id: 0,
product: "$_id",
totalReviews: 1,
averageRating: 1,
comments: 1
}
}
]).pretty( )

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.

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 22


Department of Computer Science and Business Systems

8 a. Demonstrate creation of different types of indexes on collection


(unique, sparse, compound and multikey indexes)

 Insert Sample Documents


[Link]([
{ name: "Alice", email: "alice@[Link]", dept: "HR", skills: ["communication", "leadership"]
},
{ name: "Bob", email: "bob@[Link]", dept: "Engineering", skills: ["JavaScript", "MongoDB"]
},
{ name: "Charlie", dept: "HR", skills: ["recruitment"] },
{ name: "David", email: "david@[Link]", dept: "Engineering" },
{ name: "Eve", email: "eve@[Link]", dept: "Finance", skills: ["accounting", "Excel"] }])

1. Unique Index on Email


>[Link]({ email: 1 }, { unique: true })

 Ensures no two employees can have the same email.


 If you try to insert another document with an existing email, MongoDB will throw a
duplicate key error.

2. Sparse Index on Email


>[Link]({ email: 1 }, { sparse: true })

 This only indexes documents where email exists, so it allows multiple documents
without an email field without violating the unique constraint (if unique: true is
combined).

3. Compound Index on Department and Name


>[Link]({ dept: 1, name: 1 })

Note: Optimizes queries like:


[Link]({ dept: "HR", name: "Alice" })

4. Multikey Index on Skills (Array Field)


>[Link]({ skills: 1 })
Note: This creates a multikey index because skills is an array. Enables fast queries like:
[Link]({ skills: "MongoDB" })

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 23


Department of Computer Science and Business Systems

5. View All Indexes on the Collection


>[Link]( )

b. Demonstrate optimization of queries using indexes.

 Insert Sample Documents


>[Link]([
{ name: "Laptop", category: "Electronics", price: 1000, stock: 10 },
{ name: "Smartphone", category: "Electronics", price: 500, stock: 50 },
{ name: "Desk Chair", category: "Furniture", price: 150, stock: 5 },
{ name: "Notebook", category: "Stationery", price: 5, stock: 100 },
{ name: "Monitor", category: "Electronics", price: 200, stock: 20 }
])

 Run a Query Without an Index


>[Link]({ category: "Electronics", price: { $lt: 600 } }).explain("executionStats")

 Create an Index on category and price


>[Link]({ category: 1, price: 1 })

 Re-run the Same Query with explain( ) as follows


>[Link]({ category: "Electronics", price: { $lt: 600 } }).explain("executionStats").
executionStats. totalDocsExamined

>[Link]({ category: "Electronics", price: { $lt: 600 } }).explain("executionStats").


executionStats. executionTimeMillisEstimate

Note: check the following fields in the output :


• totalDocsExamined should be lower
• executionTimeMillis should be reduced
• indexName should match the index used

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 24


Department of Computer Science and Business Systems

9 a. Develop a query to demonstrate Text search using catalog data collection


for a given word

 Create database
> use kannadaMovies
 Create collection
>[Link](‘catalog’)

 Add documents through the csv file consisting of multiple documents(using Adddata button in
mongoDB compass )

Verify the documents loaded for the collection


>[Link]( ) // number of documents

 Create a Text Index


Next, create a text index on the name and genre fields to enable text search.

>[Link]({name: "text", genre: "text"})

 Perform a Text Search Query


Now, let’s perform a text search to find documents containing a specific word.
>[Link]({$text: {$search: "maga"}}) //for name field
>[Link]({$text: {$search: "comedy"}}) // for genre field

 Perform a Text Search Query for a phrase


>[Link]({$text: {$search: ""tappida Maga""}})

b. Develop queries to illustrate excluding documents with certain words and


phrases
 Perform Queries to Exclude Documents
Use the $text operator with negation to exclude documents containing specific words or
phrases.
Example 1: Exclude Documents Containing the Word “action”
>[Link]({ $text: { $search: "crime romance -action" }, year:2021 } )

Example 2: Exclude Documents Containing the Phrase “da maga”


> [Link]({$text: {$search: 'maga -"da maga" '}})
or
>[Link]({ $text: { $search: "maga -\\\"da maga\\\"" } })

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 25


Department of Computer Science and Business Systems

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.
 Step-by-Step guide to using the aggregation pipeline in MongoDB, with examples of
various stages such as $match, $group, $sort, $project, $skip, and others.

Example: Demonstrating projection stage


>[Link]({$project:{year:'$year'}})

>[Link]({$project:{year:'$year',genre:1}})
Or
>[Link]({$project:{year:'$year',genre:’$genre’}})

Example: Demonstrating projection and limit stage


>[Link]({$project:{year:'$year',genre:'$genre'}},{$limit:5})

Example : create an aggregation pipeline that includes various stages:


$match: Filter documents to include only those in the year 2017.
$group: Group documents by genre and calculate the average rating for each genre.
$sort: Sort the results by avgRating in descending order.
$project: Include specific fields in the output
$limit: Limit the output to 5 results.
$skip: Skip the first two results

result = [Link]([
{$match: {year :2017}}, // 1. Match stage: Filter documents by year 2017
{$group: {_id: "$genre", avgRating:{$avg: "$rating"}}}, // 2. Group stage: Group by genre and
calculate average rating
{$sort: {avgRating:-1}}, // 3. Sort stage: Sort by avgRating in descending order
{$project: {year:"$year", avgRating:1, genre:1} }, // 4. Project stage: Include specific fields
{$limit:5} ]).toArray() // 5. Limit stage: Limit the output to 5 results
print("Top 5 rated movie genres with their average rating")
printjson(result)

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 26


Department of Computer Science and Business Systems

Adding another stage using ‘$skip’:

Example 2: 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 = [Link]([
{$match: {year :2017}}, // 1. Match stage: Filter documents by year 2017
{$group: {_id: "$genre", avgRating:{$avg: "$rating"}}}, // 2. Group stage: Group by genre and
calculate average rating
{$sort: {avgRating:-1}}, // 3. Sort stage: Sort by avgRating in descending order
{$project: {year:"$year", avgRating:1, genre:1} }, // 4. Project stage: Include specific fields

{$limit:7}, // 5. Limit stage: Limit the output to 7 results


{$skip:2} ]).toArray( ) // 6. Skip stage: Skip the first two results
print("Top 7 rated movie genres with their average rating with the first two skipped")
printjson(result2)

PRADEEPKUMAR G M, CSBS DEPT.,BMSIT&M 27

You might also like