MongoDb Manual
MongoDb Manual
BDSL456B
MongoDB LABORATORY
Manual
IV-SEMESTER
Prepared By:
CREDITS – 01
Course Learning objectives:
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
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
4
Program 1
a. Illustration of Where Clause, AND, OR operations in MongoDB.
db.students.insertOne({
_id: 1,
name: "Alice",
age: 21,
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:
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" }
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:
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 }
] } ] })
This means both condition1 must be true, and either condition2 or condition3 must be true.
Example:
{ $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 })
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 }
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 })
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.
9
Program 2
a. Develop a MongoDB query to select certain fields and ignore some fields of
the documents from any collection.
//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" }
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.
// 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.
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:
12
>db.locations.find(
location:
{ $near :
$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([
])
>db.collection.find( { a: { $bitsAllClear: [ 1, 5 ] } } )
>db.collection.find( { a: { $bitsAllSet: [ 1, 5 ] } } )
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,
"authors": [
"age": 35
},
"age": 40
$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] }
]
)
// 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" } } } ])
Example: Suppose we want to push a new sale value to the existing sales array:
$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:
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:
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}
]
}
]
$group: Group documents by a specified key and perform aggregation operations on grouped data.
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" } }
}
},
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
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"
}
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:
24
Program 8
Unique index:
Now, if I insert a new document that has name already exists in the collection, the MongoDB server
will throw an error:
Sparse Index:
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:
Multikey Index:
db.users.createIndex({ "author": 1 })
8b) >>db.book.find({rating:5}).explain(‘executionStats’);
25
Program 9
a. Develop a query to demonstrate Text search using catalog data collection for
a given word
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"
}
]);
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:
Now, you can perform a text search on the collection. For example, to search for the word "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.
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
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
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