MongoDB Lab Manual AI DS 2024 25
MongoDB Lab Manual AI DS 2024 25
‘JnanaPrabha’,VirgoNagarPost,Bengaluru-560049
LABORATORYMANUAL
SEMESTER : IV
SUBJECT : MONGO DB
NAME: _ _ _ _ _ _ _ _ _ _ _ _
USN: _ _ _ _ _ _ _ _ _ _ __ _
SECTION:_ _ _ _ _ _ _ _ _ _ _ _
BATCH:_ _ _ _ _ _ _ _ _ _ __ _
PROGRAM OUTCOMES
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.
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.
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
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.
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.
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.
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 .
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.
Slower compared to
Faster, particularly for
Performance MongoDB for large
handling large-scale data
datasets
>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.
>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') }
>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})
Program 2
Out Put:
{
rno: 1,
name: 'Bhavana'
}
{
rno: 2,
name: 'Amith'
}
{
rno: 3,
name: 'Sagar'
}
>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 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'
}
Out Put:
{
name: 'Bhavana'
}
{
name: 'Amith'
}
{
name: 'Sagar'
}
>db.details.find({},{rno:1,name:1,_id:0}).limit(5)
>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
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
}
Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9ced'),
name: 'Rohith',
age: 30,
department: 'HR',
salary: 50000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf0'),
name: 'Nandini',
age: 35,
department: 'Marketing',
salary: 60000
}
Out Put:
{
_id: ObjectId('678f2ad15da59490c6dd9cee'),
name: 'Sharath',
age: 24,
department: 'Engineering',
salary: 70000
}
{
_id: ObjectId('678f2ad15da59490c6dd9cf1'),
name: 'Ashwin',
age: 28,
department: 'Finance',
salary: 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
}
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
}
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] } }
])
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.
>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
])
Out Put:
{
_id: ObjectId('6653703d4e38f292e52202d8'),
name: 'Device A',
status: 5
},
{
_id: ObjectId('6653703d4e38f292e52202dc'),
name: 'Device E',
status: 7
}
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
}
Out Put:
{
_id: ObjectId('6653703d4e38f292e52202d8'),
name: 'Device A',
status: 5
}
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!'
}
]
}
Out Put:
{
_id: ObjectId('6790f80204871f2f43db7636'),
reviews: [
{
user: 'Alice',
rating: 5,
comment: 'Excellent!'
}
]
}
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
}
Out Put:
{
_id: 'Amar',
products: [
'Laptop',
'Keyboard'
]
}
{
_id: 'Babu',
products: [
'Laptop',
'Monitor'
]
}
{
_id: 'Chandra',
products: [
'Mouse'
]
}
{
_id: 'Deva',
products: [
'Laptop'
]
}
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.
Out Put:
{
averageRating: 4.5,
totalReviews: 2,
restaurant: 'Curry Palace'
}
{
averageRating: 4.5,
totalReviews: 2,
restaurant: 'Taco Stand'
}
Program 7
>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"
}
}
])
{
_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.
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.
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' }
].
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
Step2:CreateCatalog collection
Step3:click on import data button
Step4:select csv file click on import.
>db.catalog.countDocuments()
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'
}
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.
{$match:{year :2017}},
{$sort: {avgRating:-1}},
{$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 }
]
>result2 = db.catalog.aggregate([
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 }
]