0% found this document useful (0 votes)
213 views29 pages

MongoDb Manual

The document is a laboratory manual for a MongoDB course at the Bangalore Institute of Technology, detailing course objectives, lab programs, and expected outcomes. It includes practical exercises on MongoDB commands, queries, indexing, and aggregation operations. The manual also provides syntax examples for various MongoDB operations like insert, update, delete, and query selectors.

Uploaded by

chiragmohite02
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)
213 views29 pages

MongoDb Manual

The document is a laboratory manual for a MongoDB course at the Bangalore Institute of Technology, detailing course objectives, lab programs, and expected outcomes. It includes practical exercises on MongoDB commands, queries, indexing, and aggregation operations. The manual also provides syntax examples for various MongoDB operations like insert, update, delete, and query selectors.

Uploaded by

chiragmohite02
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/ 29

BANGALORE INSTITUTE OF TECHNOLOGY

K.R.ROAD, V.V.PURAM, BANGALORE-560 004

Department of Artificial Intelligence & Machine Learning

BDSL456B

MongoDB LABORATORY

Manual

IV-SEMESTER

Prepared By:

Prof. YAMINI SAHUKAR P.


MongoDB LABORATORY
SEMESTER – IV
Course Code: BDSL456B IA Marks: 50
Number of Lecture Hours/Week 0:2:0 Total Hours: 24

CREDITS – 01
Course Learning objectives:

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.

Lab Programs:
Sl.
Name of Program
No.
a. Illustration of Where Clause, AND, OR operations in MongoDB.
1 b. Execute the Commands of MongoDB and operations in MongoDB: Insert, Query,
Update, Delete and Projection. (Note: use any collection).
a. Develop a MongoDB query to select certain fields and ignore some fields of the
documents from any collection.
2
b. Develop a MongoDB query to display the first 5 documents from the results obtained
in a. [use of limit and find]
a. Execute query selectors (comparison selectors, logical selectors) and list out the results
on any collection
3
b. Execute query selectors (Geospatial selectors, Bitwise selectors) and list out the results
on any collection
Create and demonstrate how projection operators ($, $elematch and $slice) would be
4
used in the MongoDB.

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

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)

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.
b. Using E-commerce collection write a query to display reviews summary.
a. Demonstrate creation of different types of indexes on collection (unique, sparse,
8 compound and multikey indexes)
b. Demonstrate optimization of queries using indexes.
a. Develop a query to demonstrate Text search using catalog data collection for a given
9 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.

Laboratory outcomes:
At the end of the course students should be able to:
1. Make use of MongoDB 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.

50 marks lab component is split up into 30 marks for the conduction of the experiment and
preparation of laboratory record each program should be evaluated for 10 marks, and 20 marks for
the test to be conducted after the completion of all the laboratory sessions.
//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'})

// create student details like name, rno, email,location,address,marks

//Every row/document can be different than other


> db.details.insert({name:'Amit',rno:2})
> db.details.insert({rno:3, email_id:'[email protected]'})

// To display data from collection


> db.details.find()
{ "_id" : ObjectId("5d7d3daf315728b4998f522e"), "rno" : 1, "name" : "Bhavana" }
{ "_id" : ObjectId("5d7d3f28315728b4998f522f"), "name" : "Amit", "rno" : 2 }

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

Example Collection: students

db.students.insertOne({

_id: 1,

name: "Alice",

age: 21,

course: "AI & ML",

marks: { math: 85, science: 90 },

enrolled: true

})

db.students.insertMany([

{ _id: 1, name: "Alice", age: 21, course: "AI & ML", marks: 85, enrolled: true },

{ _id: 2, name: "Bob", age: 22, course: "DBMS", marks: 78, enrolled: true },

{ _id: 3, name: "Charlie", age: 20, course: "OS", marks: 82, enrolled: false },

{ _id: 4, name: "David", age: 23, course: "Networks", marks: 90, enrolled: true },

{ _id: 5, name: "Eve", age: 21, course: "Data Structures", marks: 89, enrolled: false }

])

Where Clause in MongoDB: In MongoDB, the find() method is used to query documents from a
collection. The find() method can accept a query document as a parameter which acts as a "WHERE"
clause.
Syntax: db.collection.find({ field: value })

Example1:

To filter students who are 22 years old:

db.students.find({ age: 22 })

Output:

[
{ "_id": 1, "name": "Alice", "age": 22, "course": "AIML", "score": 85 },
{ "_id": 3, "name": "Charlie", "age": 22, "course": "AIML", "score": 90 }

5
]

Example 2:
> db.details.find()
{ "_id" : ObjectId("5d7d3daf315728b4998f522e"), "rno" : 1, "name" : "Bhavana" }
{ "_id" : ObjectId("5d7d3f28315728b4998f522f"), "name" : "Amit", "rno" : 2 }
{ "_id" : ObjectId("5d7d3f56315728b4998f5230"), "rno" : 3, "email_id" : "[email protected]" }
{ "_id" : 1, "rno" : 4, "name" : "Akash" }

//findOne to show only first record


> db. details.findOne()
{
"_id" : ObjectId("5d83af5aa44331f62bcd8369"),
"rno" : 1,
"name" : "Ashiti"
}

AND Operation in MongoDB: MongoDB provides the $and operator to perform logical AND
operation between multiple conditions in a query.
Syntax: db.collection.find({ $and: [ { field1: value1 }, { field2: value2 } ] })

Example 1:

To find students who are 22 years old AND enrolled in AIML:

db.students.find({ $and: [ { age: 22 }, { course: "AIML" } ] })

OR (Shorter version as MongoDB treats multiple conditions as AND by default):

db.students.find({ age: 22, course: "AIML" })

Output:

[
{ "_id": 1, "name": "Alice", "age": 22, "course": "AIML", "score": 85 },
{ "_id": 3, "name": "Charlie", "age": 22, "course": "AIML", "score": 90 }
]

Example 2:
>db.details.find({$and: [{"location": "chennai"}, {"location": "delhi"}] })

OR Operation in MongoDB: Similarly, MongoDB provides the $or operator to perform logical
OR operation between multiple conditions in a query.
Syntax: db.collection.find({ $or: [ { field1: value1 }, { field2: value2 } ] })
Example 1:

To find students who are either 22 years old OR have a score above 80:
6
db.students.find({ $or: [ { age: 22 }, { score: { $gt: 80 } } ] })

Output:

[
{ "_id": 1, "name": "Alice", "age": 22, "course": "AIML", "score": 85 },
{ "_id": 3, "name": "Charlie", "age": 22, "course": "AIML", "score": 90 }
]
Example 2:
>db.details.find({$or: [{"location": "chennai"}, {"location": "delhi"}] })

In MongoDB, you can combine AND ($and) and OR ($or) conditions in a single query for more
complex filtering.

Syntax: db.collection.find({ $and: [ { field1: value1 }, { $or: [ { field2: value2 }, { field3: value3 }
] } ] })

db.collection.find({$and: [{ condition1 },{ $or: [ condition2, condition3 ] }]})

This means both condition1 must be true, and either condition2 or condition3 must be true.

Example:

db.students.find({$and: [{ enrolled: true }, // AND condition: Student must be enrolled

{ $or: [ { marks: { $gt: 80 } }, { age: { $lt: 21 } } ] } // OR condition: Marks > 80 OR Age < 21

})

7
b. Execute the Commands of MongoDB and operations in MongoDB: Insert, Query,
Update, Delete and 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({name:'Amit',rno:2})
> db.details.insert({rno:3, email_id:'[email protected]'})

// To insert date use ISODate function


> db.emp.insert({rno:15, name:'Ravina', dob: ISODate("2019-09-14")})

db.details.insert({rno:6,dob:new Date(Date.now())})
db.details.insert([{rno:18,doj:Date()}])
db.details.insert({rno:7,dob:ISODate("1990-12-31")}) //yyyy-mm-dd

// trying to insert data with duplicate _id, it will not accept as _id is primary key field
> db.details.insert({_id:1,rno:5,name:"Reena"})
E11000 duplicate key error index: db1.emp.$_id_ dup key: { : 1.0 }

//Insert multiple documents at once


> db.details.insert([{rno:7,name:'a'},{rno:8,name:'b'},{rno:8,name:'c'}])

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


> db.emp.insert({rno:10,name:'Ankit',hobbies:['singing','cricket','swimming',’music’],age:21})

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

Update Operation: Use the updateOne() method to update a single document in a collection.
Syntax: db.collection.updateOne( { field: value }, { $set: { fieldToUpdate: newValue } })

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

//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 to
include 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" }

9
Program 2

a. Develop a MongoDB query to select certain fields and ignore some fields of
the documents from any collection.

Syntax: db.collection.find({}, { field1: 1, field2: 1, _id: 0 })


 db.collection.find({}) is used to retrieve all documents from the collection.
 { 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:5},{name:1})
{ "_id" : ObjectId("5d83af5aa44331f62bcd836d"), "name" : "Jivan" }

//Find command with condition with giving name field only to show and _id to hide
> db. details.find({rno:5},{name:1,_id:0})
{ "name" : "Jivan" }

// Find command to show only names without condition


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

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 particularly
useful 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)


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

// Limit use to show only some records from starting- following command shows only first 2
records from collection
> db. details.find().limit(2)
{ "_id" : ObjectId("5d83af5aa44331f62bcd8369"), "rno" : 1, "name" : "Ashiti" }
{ "_id" : ObjectId("5d83af5aa44331f62bcd836a"), "rno" : 2, "name" : "Savita" }
10
Program 3

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

Comparison Selectors: Comparison selectors are used to compare fields against specific values or
other 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 are
some 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 query
expression.
$nor - Joins query clauses with a logical NOR and requires that none of the conditions be true.

>db.collection.find({
$and: [
{ age: { $gte: 18 } }, // age greater than or equal to 18
{ age: { $lt: 30 } }, // age less than 30
{ gender: "male" }, // gender equals "male"
{ city: { $in: ["New York", "Los Angeles"] } } // city is either "New York" or "Los Angeles"
]
})

11
b. Execute query selectors (Geospatial selectors, Bitwise selectors) and list out
the results on any collection
Geospatial Selectors: MongoDB supports geospatial queries for geospatial data. It provides two
types of geospatial indexes: 2d indexes and 2d sphere indexes.

Name Description
$geoIntersects Selects geometries that intersect with a GeoJSON geometry.
The 2dsphere index supports $geoIntersects.

$geoWithin Selects geometries within a bounding GeoJSON geometry.


The 2dsphere and 2d indexes support $geoWithin.

$near Returns geospatial objects in proximity to a point. Requires a geospatial


index. The 2dsphere and 2d indexes support $near.

Example: Let's say we have a collection named "locations" with documents containing location data:

{
"_id": ObjectId("60cf9df572f71e01c86bf703"),
"name": "Store A",
"location": { "type": "Point", "coordinates": [40.7128, -74.0060] }
},
{
"_id": ObjectId("60cf9df572f71e01c86bf704"),
"name": "Store B",
"location": {"type": "Point", "coordinates": [34.0522, -18.2437] }
},
{
"_id": ObjectId("60cf9df572f71e01c86bf705"),
"name": "Store C",
"location": { "type": "Point", "coordinates": [51.5074, -10.1278] }
}
To perform a geospatial query to find stores within a certain radius of a given location, you can use
the $near operator:

First create a index and query using near.

>db.collection.createIndex( { location : "2dsphere" } )

12
>db.locations.find(

location:

{ $near :

$geometry: { type: "Point", coordinates: [ -73.9667, 40.78 ] },

$minDistance: 1000,

$maxDistance: 5000

This query will return stores within 10 kilometers of New York City.

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.
Name Description
$bitsAllClear Matches numeric or binary values in which a set of bit positions all have a
value of 0.

$bitsAllSet Matches numeric or binary values in which a set of bit positions all have a
value of 1.

$bitsAnyClear Matches numeric or binary values in which any bit from a set of bit positions
has a value of 0.

$bitsAnySet Matches numeric or binary values in which any bit from a set of bit positions
has a value of 1.

Position List

If querying a list of bit positions, each <position> must be a non-negative integer. Bit positions start at
0 from the least significant bit. For example, the decimal number 254 would have the following bit positions:

13
Bit value 1 1 1 1 1 1 1 1

Position 7 6 5 4 3 2 1 0

>db.collection.insertMany([

{ _id: 1, a: 54, binaryValueofA: "00110110" },

{ _id: 2, a: 20, binaryValueofA: "00010100" },

{ _id: 3, a: 20.0, binaryValueofA: "00010100" }

])

>db.collection.find( { a: { $bitsAllClear: [ 1, 5 ] } } )

Output: { "_id" : 2, "a" : 20, "binaryValueofA" : "00010100" }

{ "_id" : 3, "a" : 20, "binaryValueofA" : "00010100" }

>db.collection.find( { a: { $bitsAllSet: [ 1, 5 ] } } )

Output: { "_id" : 1, "a" : 54, "binaryValueofA" : "00110110" }

14
Program 4

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

$elemMatch: The $elemMatch operator is used to match documents that contain an array field with at
least one element that matches all the specified query criteria.

"_id": 1,

"title": "MongoDB Basics",

"authors": [

"name": "John Doe",

"age": 35

},

"name": "Jane Smith",

"age": 40

>db.books.find({ authors: { $elemMatch: { age: { $gt: 35 } } } })

$slice: The $slice projection operator is used within the projection document to limit the number of
elements returned from an array field.

db.student2.insert([
{ "_id": 1, "name": "Alice", "grades": [85, 90, 78] },
{ "_id": 2, "name": "Bob", "grades": [95, 88, 82] },
{ "_id": 3, "name": "Charlie", "grades": [72, 92, 80] },
{ "_id": 4, "name": "David", "grades": [80, 85, 90] },

15
{ "_id": 5, "name": "Emily", "grades": [75, 87, 89] }
]
)

>db.student.find( {}, { "grades": { $slice: 2 } } )


>db.student.find( {}, { "grades": { $slice: -3 } } )

// To project only the first element in the grades array that is greater than or equal to 85, we can use
the following query:
>db.student.find( { grades: { $gte: 85 } }, { "grades.$": 1 } )

//grades array contains at least one element that is greater than or equal to 85 and less than or equal
to 90.
>db.students.find( { grades: { $elemMatch: { $gte: 85, $lte: 90 } } }, { name: 1, grades: 1 } )

16
Program 5

Execute Aggregation operations ($avg, $min, $max, $push, $addToSet etc.) Encourage
students to execute several queries to demonstrate various aggregation operators.
$avg: Calculates the average value of the numeric values in a specified array.

Example: Suppose we have a collection named "sales" with documents containing sales data:

{
"_id": ObjectId("60cf9df572f71e01c86bf703"),
"product": "A",
"sales": [100, 150, 200]
},
{
"_id": ObjectId("60cf9df572f71e01c86bf704"),
"product": "B",
"sales": [120, 130, 140]
}
>db.sales.aggregate([ { $project: { product: 1, averageSales: { $avg: "$sales" } } } ])

$min: Finds the minimum value in a specified array.

Example: To find the minimum sales value for each product:

>db.sales.aggregate([ { $project: { product: 1, minSales: { $min: "$sales" } } } ])

$max: Finds the maximum value in a specified array.

Example: To find the maximum sales value for each product:

>db.sales.aggregate([ { $project: { product: 1, maxSales: { $max: "$sales" } } } ])

$push: Adds a value to an array field in each document.

Example: Suppose we want to push a new sale value to the existing sales array:

>db.sales.aggregate([ { $project: { product: 1, sales: { $push: 250 } } } ])

$addToSet: Adds a value to an array field only if the value is not already present.

Example: Suppose we want to add a new customer to the list of customers for each product:

>db.sales.aggregate([ { $project: { product: 1, customers: { $addToSet: "New Customer" } } } ])

17
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)

Aggregation Pipeline:

An aggregation pipeline consists of one or more stages that process documents:

 Each stage performs an operation on the input documents. For example, a stage can filter
documents, group documents, and calculate values.

 The documents that are output from a stage are passed to the next stage.

 An aggregation pipeline can return results for groups of documents. For example, return the
total, average, maximum, and minimum values.

Example: Suppose we have a collection named "students" with documents containing information
about students and their exam scores:
[
{
"_id": ObjectId("60cf9df572f71e01c86bf703"),
"name": "Alice",
"age": 18,
"examScores": [
{"subject": "Math", "score": 80},
{"subject": "Science", "score": 75}
]
},
{
"_id": ObjectId("60cf9df572f71e01c86bf704"),
"name": "Bob",
"age": 20,
"examScores": [
{"subject": "Math", "score": 90},
{"subject": "Science", "score": 85}
]
},
{
"_id": ObjectId("60cf9df572f71e01c86bf705"),
"name": "Charlie",
"age": 19,
"examScores": [

18
{"subject": "Math", "score": 85},
{"subject": "Science", "score": 80}
]
}
]

Let's create an aggregation pipeline to perform various operations:

$match: Filter documents based on specified criteria.

$group: Group documents by a specified key and perform aggregation operations on grouped data.

$sort: Sort documents based on specified criteria.

$project: Reshape documents by including, excluding, or modifying fields.

$skip: Skip a specified number of documents.

db.students.aggregate([
// Stage 1: Filter students who are at least 18 years old
{ $match: { age: { $gte: 18 } } },

// Stage 2: Group students by age and calculate average exam score for each age group
{
$group: {
_id: "$age",
averageScore: { $avg: { $avg: "$examScores.score" } }
}
},

// Stage 3: Sort age groups by average score in descending order


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

// Stage 4: Project to include only age and averageScore fields


{
$project: {
_id: 0,
age: "$_id",
averageScore: 1
}
},
19
// Stage 5: Skip the first 1 document
{ $skip: 1 }
])

This aggregation pipeline will filter students, who are at least 18 years old, group them by age, calculate
the average exam score for each age group, sort the age groups by average score in descending order,
include only the age and average Score fields in the output, and skip the first document.

20
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.

db.listingsAndReviews.insertMany([
{
listing_url: "http://example.com/listing1",
name: "Beautiful Apartment",
address: "123 Main St, Anytown, USA",
host: {
picture_url: "http://example.com/host1.jpg"
}
},
{
listing_url: "http://example.com/listing2",
name: "Cozy Cottage",
address: "456 Oak St, Anytown, USA",
host: {
picture_url: "http://example.com/host2.jpg"
}
},
{
listing_url: "http://example.com/listing3",
name: "Modern Condo",
address: "789 Pine St, Anytown, USA",
host: {}
}
]);

Aggregate pipeline:

db.listingsAndReviews.aggregate([
{
$match: {
"host.picture_url": { $exists: true, $ne: null }
}
},
{
$project: {
listing_url: 1,
name: 1,
address: 1,
host_picture_url: "$host.picture_url"
}
}
21
]).forEach(doc => printjson(doc));

22
Explanation:

1. $match: This stage filters the documents to include only those where the host.picture_url field
exists and is not null.
2. $project: This stage includes only the listing_url, name, address, and host_picture_url fields in the
output. The host_picture_url is aliased from the host.picture_url field.

Output:

{
"listing_url": "http://example.com/listing1",
"name": "Beautiful Apartment",
"address": "123 Main St, Anytown, USA",
"host_picture_url": "http://example.com/host1.jpg"
}
{
"listing_url": "http://example.com/listing2",
"name": "Cozy Cottage",
"address": "456 Oak St, Anytown, USA",
"host_picture_url": "http://example.com/host2.jpg"
}

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

db.ecommerce.insertMany([
{
product_id: "P001",
review_id: "R001",
review_text: "Great product!",
rating: 5,
review_date: ISODate("2023-06-01")
},
{
product_id: "P001",
review_id: "R002",
review_text: "Good value for money.",
rating: 4,
review_date: ISODate("2023-07-01")
},
{
product_id: "P002",
review_id: "R003",
review_text: "Not satisfied with the quality.",
rating: 2,
review_date: ISODate("2023-06-15")
23
},
{
product_id: "P002",
review_id: "R004",
review_text: "Excellent customer service.",
rating: 5,
review_date: ISODate("2023-07-10")
}
]);

Aggregate pipeline:

db.ecommerce.aggregate([
{
$group: {
_id: "$product_id",
totalReviews: { $sum: 1 },
averageRating: { $avg: "$rating" },
mostRecentReview: { $max: "$review_date" }
}
},
{
$project: {
_id: 0,
product_id: "$_id",
totalReviews: 1,
averageRating: { $round: ["$averageRating", 1] },
mostRecentReview: 1
}
}
]);

Explanation:

1. $group: Groups the documents by product_id and calculates:


o totalReviews: The total number of reviews for each product using $sum.
o averageRating: The average rating for each product using $avg.
o mostRecentReview: The most recent review date for each product using $max.
2. $project: Projects the required fields:
o product_id: The product ID.
o totalReviews: The total number of reviews.
o averageRating: The average rating, rounded to one decimal place using the $round operator.
o mostRecentReview: The most recent review date.s

24
Program 8

a. Demonstrate creation of different types of indexes on collection (unique,


sparse, compound and multikey indexes)
b. Demonstrate optimization of queries using indexes.

Create a book collection and insert id,name,rating and list of authors

Unique index:

db.users.createIndex({ "name": 1 }, { unique: true })

Now, if I insert a new document that has name already exists in the collection, the MongoDB server
will throw an error:

Sparse Index:

db.users.createIndex({ "rating": 1 }, { sparse: true })

Use Cases for Sparse Indexes:

Optional Fields: If a field in your collection is optional (i.e., not present in all documents), a sparse
index can be a good choice to optimize storage and write performance.

Null Values: If you anticipate many documents with null values for the indexed field, a sparse index
can help avoid storing unnecessary null entries in the index, saving space.

Compound Index:

db.users.createIndex({ "name": 1, "id": 1 })

Multikey Index:

db.users.createIndex({ "author": 1 })

Assuming interests is an array field in the user documents.

8b) >>db.book.find({rating:5}).explain(‘executionStats’);

Execute this before and after index and explain optimization.

25
Program 9

a. Develop a query to demonstrate Text search using catalog data collection for
a given word

Step 1: Insert Sample Data into the Collection

Let's insert some sample data into a catalog collection:

db.catalog.insertMany([
{
title: "Introduction to MongoDB",
description: "This book provides an overview of MongoDB features and architecture.",
author: "John Doe"
},
{
title: "Mastering JavaScript",
description: "A comprehensive guide to JavaScript programming.",
author: "Jane Smith"
},
{
title: "Node.js Design Patterns",
description: "Best practices and design patterns for Node.js development.",
author: "Alex Johnson"
},
{
title: "Advanced MongoDB",
description: "In-depth coverage of advanced MongoDB features and performance optimization.",
author: "Emily Davis"
}
]);

Step 2: Create a Text Index

Create a text index on the fields you want to search. In this example, we will create a text index on the title
and description fields:

db.catalog.createIndex({ title: "text", description: "text" });

Step 3: Perform a Text Search

Now, you can perform a text search on the collection. For example, to search for the word "MongoDB":

db.catalog.find({ $text: { $search: "MongoDB" } });

26
Explanation

1. Inserting Data: The insertMany() method inserts sample documents into the catalog collection.
2. Creating Text Index: The createIndex() method creates a text index on the title and description
fields.
3. Performing Text Search: The find() method with $text operator searches for the specified word in
the indexed fields.

By following these steps, you can effectively demonstrate text search functionality in MongoDB using a
catalog data collection.

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


phrases.

Exclude Documents Containing a Single Word

To exclude documents that contain the word "JavaScript":

db.catalog.find({ $text: { $search: "MongoDB -JavaScript" } });

Exclude Documents Containing a Phrase

To exclude documents that contain the phrase "design patterns":

db.catalog.find({ $text: { $search: 'MongoDB -"design patterns"' } });

Performing Text Search with Exclusions:

 The first query searches for documents containing "MongoDB" but excludes those with
"JavaScript".
 The second query searches for documents containing "MongoDB" but excludes those with the
phrase "design patterns".

27
Program 10

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

Step 1: Insert Sample Data

db.catalog.insertMany([
{
title: "Introduction to MongoDB",
description: "This book provides an overview of MongoDB features and architecture.",
author: "John Doe",
price: 29.99,
tags: ["database", "nosql"]
},
{
title: "Mastering JavaScript",
description: "A comprehensive guide to JavaScript programming.",
author: "Jane Smith",
price: 39.99,
tags: ["programming", "javascript"]
},
{
title: "Node.js Design Patterns",
description: "Best practices and design patterns for Node.js development.",
author: "Alex Johnson",
price: 49.99,
tags: ["programming", "nodejs"]
},
{
title: "Advanced MongoDB",
description: "In-depth coverage of advanced MongoDB features and performance optimization.",
author: "Emily Davis",
price: 59.99,
tags: ["database", "nosql"]
},
{
title: "JavaScript: The Good Parts",
description: "A detailed exploration of the strengths of JavaScript.",
author: "Douglas Crockford",
price: 19.99,
tags: ["programming", "javascript"]
}
]);

28
Step 2: Create a Text Index

Create a text index on the fields you want to search:

db.catalog.createIndex({ title: "text", description: "text" });

Step 3: Develop the Aggregation Pipeline

Here, we will perform a text search for the term "JavaScript" and then sort the results by price in
descending order:

db.catalog.aggregate([
{
$match: {
$text: { $search: "JavaScript" }
}
},
{
$sort: { price: -1 }
},
{
$project: {
title: 1,
description: 1,
author: 1,
price: 1,
score: { $meta: "textScore" }
}
}
]);

Explanation

 Inserting Data: The insertMany() method inserts sample documents into the catalog collection.
 Creating Text Index: The createIndex() method creates a text index on the title and description
fields.
 Aggregation Pipeline:
o $match: Filters documents that match the text search term "JavaScript".
o $sort: Sorts the results by the price field in descending order.
o $project: Selects the fields to include in the output and includes the text search score.

29

You might also like