LIST OF EXPERIMENTS
MONGODB LABORATORY
Course Code BDSL456B 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 Exam Hours 03
Course Objectives:
● Understand basic MongoDB functions, operators and types of operations in MongoDB.
● Installing and configuring MongoDB in windows.
● Perform all database operations using MongoDB.
● Demonstrate the use of Indexing, Advanced Indexing in MongoDB.
● Apply the aggregation and Map Reduction in MongoDB.
Note: Two hours tutorial is suggested for each laboratory sessions.
Prerequisite
● Students should be familiarized about MongoDB Compass environment
and on Mongosh to execute queries.
● Creation of Database, collections and documents should be introduced.
Sl. No. PART A – List of problems for which student should develop queries and execute in the
Laboratory
Aim: To introduce the Insert, Query, Update, Delete, Projection and understand use of AND, OR
operators.
1
Program:
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.( use any collection)
Aim: To understand use of limit and find
2 Program:
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]
Aim: To understand different query selectors.
Program:
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
Aim: To understand projection operators.
Program: Create and demonstrate how projection operators ($, $elematch and $slice) would be used
4
in the MongoDB.
Aim: To understand Aggregation operations.
5 Program: Execute Aggregation operations ($avg, $min,$max, $push, $addToSet etc.). students
encourage to execute several queries to demonstrate various aggregation operators)
Aim: To understand Pipeline and its operations
6 Program: 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 Aim: To understand all listings
Program:
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 Aim: To understand different types of collection using index.
Program:
a. Demonstrate creation of different types of indexes on collection (unique, sparse, compound and
multikey indexes)
b. Demonstrate optimization of queries using indexes.
9 Aim: To understand text search using collection for a given word
Program:
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
Aim: To understand aggregation pipeline operations using text search on catalog data.
10
Program: Develop an aggregation pipeline to illustrate Text search on Catalog data
collection.
Course Outcome (Course Skill Set)
At the end of the course the student will be able to:
1. Make use of MangoDB commands and queries.
2. Illustrate the role of aggregate pipelines to extract data.
3. Demonstrate optimization of queries by creating indexes.
4. Develop aggregate pipelines for text search in collections.
Assessment Details (both CIE and SEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%. The
minimum passing mark for the CIE is 40% of the maximum marks (20 marks). A student shall be deemed to
have satisfied the academic requirements and earned the credits allotted to each course. The student has to secure
not less than 35% (18 Marks out of 50) in the semester-end examination (SEE).
Continuous Internal Evaluation (CIE):
CIE marks for the practical course is 50 Marks.
The split-up of CIE marks for record/ journal and test are in the ratio 60:40.
● Each experiment to be evaluated for conduction with observation sheet and record write-up.
DATABASE
A database is a structured collection of data that is organized and stored in a computer system.
It allows for efficient storage, retrieval, and manipulation of data. Databases are used in wide
range of applications, including websites, business applications, scientific research and more.
There are various types of databases, including:
1. Relational Databases: These are the most common type of database, where data is
organized into tables with rows and columns. Relational databases use Structured Query
Language (SQL) for querying and managing data. Examples include MySQL, PostgreSQL,
Oracle Database, and Microsoft SQL Server.
2. NoSQL Databases: NoSQL (Not Only SQL) databases are designed to handle large
volumes of unstructured or semi-structured data. They provide more flexibility and
scalability compared to relational databases and are often used in big data and real-time web
applications. Examples include MongoDB, Cassandra, Redis, and Couchbase.
3. Graph Databases: Graph databases are designed to represent and store data as nodes,
edges, and properties, which are interconnected. They are used for applications where
relationships between data points are important, such as social networks, recommendation
systems, and network analysis. Examples include Neo4j, Amazon Neptune, and ArangoDB.
4. Document Databases: Document databases store and retrieve data in a semi-structured
format, typically using JSON or XML documents. They are suitable for content
management systems, e-commerce platforms, and other applications where data varies in
structure. Examples include MongoDB, Couchbase, and RavenDB.
5. Columnar Databases: Columnar databases store data in columns rather than rows, which
allows for efficient data retrieval and analysis, especially for analytical queries on large
datasets. They are commonly used in data warehousing and business intelligence
applications. Examples include Google BigQuery, Amazon Redshift, and Apache
Cassandra.
Databases play a crucial role in modern computing by enabling organizations to efficiently
manage and utilize large volumes of data for various purposes, such as decision-making,
analytics, and application development.
Introduction to MongoDB
MongoDB is a popular open-source NoSQL database management system that provides high
performance, high availability, and easy scalability. Here's a comprehensive overview of
MongoDB:
Introduction to MongoDB:
● MongoDB is a document-oriented NoSQL database.
● Developed by MongoDB Inc.
● Initially released in 2009.
● Written in C++, C
Fig: Mapping relational database to MongoDB
Features of MongoDB
1. MongoDB provides high performance. Most of the operations in the MongoDB are
faster compared to relational databases.
2. MongoDB provides auto replication feature that allows you to quickly recover data
incase of a failure.
3. Horizontal scaling is possible in MongoDB because of sharing. Sharding is partitioning
of data and placing it on multiple machines in such a way that the order of the data is
preserved.
● Collections in MongoDB is equivalent to the tables in RDBMS.
● Documents in MongoDB is equivalent to the rows in RDBMS.
● Fields in MongoDB is equivalent to the columns in RDBMS.
● Fields (key and value pairs) are stored in document; documents are stored in
collection and collections are stored in database.
This is how a document looks in MongoDB: As you can see this is similar to the row in
RDBMS. The only difference is that they are in JSON format.
Components:
1.MongoDB Server: The core database server responsible for data storage, retrieval and
manipulation.
2. MongoDB Shell: A command-line interface for interacting with MongoDB instances using
like syntax.
3. MongoDB Compass: A graphical user interface (GUI) tool for visually exploring and
interacting with MongoDB databases
SQL V/s MongoDB
SQL NoSQL
SQL are relational database NoSQL Database are non-relational
database
They are structured table to store data in They provide flexibility in data storage,
rows and columns allowing varied data types and structures.
Suitable for applications with well-defined Ideal for application with dynamic or
schemas and fixed data structured evolving data models
E-commerce platform, HR management CMS, Social media platform, Gaming
platform
Ex: MySQL, Oracle, PostgreSQL Ex: MongoDB, Cassandra, Redis
MongoDB Terminology
MongoDB is a powerful NoSQL database system that offers flexibility, scalability, and
performance, making it suitable for a wide range of applications from small-scale projects to
enterprise-level deployments. Its document-oriented nature, rich query capabilities, and ease
of scalability make it a popular choice among developers and organizations seeking a modern
database solution.
Table v/s Collection
As you see columns are represented as key-value pairs (JSON Format), rows are represented
as documents. MongoDB automatically inserts a unique id (12-byte field) field in every
document, this serves as primary key for each document. Another thing about MongoDB is
that it supports dynamic schema which means one document of a collection can have fields
while the other document has only 3 fields. This is not possible in relational database.
MongoDB, being a highly flexible and scalable NoSQL database, is widely used in various
real-time applications due to its ability to handle large volumes of data, high availability, and
horizontal scalability. Here are some real-time applications where MongoDB is commonly
used:
1. Social Media Platforms
2. IoT (Internet of Things)
3. Real-Time Analytics
4. Online Gaming
5. Financial Services
6. Real-Time Collaboration Tools
7. Content Management Systems (CMS)
8. E-commerce
How to install and Configure MongoDB for Windows
Install MongoDB on Windows:
Step 1: Go to MongoDB download Page and click download as shown in the screenshot.
https://www.mongodb.com/try/download/community a .msi file like this mongodb win32-
x86_64-2008plus-ssl-3.4.7-signed will be downloaded in your system. Double click on the
file to run the installer.
Step 2: Click Next when the MongoDB installation windows pop up.
Step 3: Accept the MongoDB user Agreement and click Next.
Step 4: When the setup asks you to choose the Setup type, choose Complete.
Step 5: Click Install to begin the installation.
Step 6: That’s it. Click Finish once the MongoDB installation is complete.
MongoDB Compass
Click on connect to make connection with server
Create Database
Give a name to create Database and for Collection
MONGOSHELL
A command-line interface for interacting with MongoDB instances using -like
syntax. Install Mongosh on your system and verify with a command “mongosh”
and try with show databases.
Experiment 1:
Aim: Introduce the Insert, Query, Update, Delete, Projection and understand use of
AND, OR operators
a. Illustration of Where Clause, AND, OR operations in MongoDB:
// Find documents where age is greater than 25 and gender is "male"
db.collection.find({ $and: [{ age: { $gt: 25 } }, { gender: "male" }] })
// Find documents where age is greater than 30 or gender is "female"
db.collection.find({ $or: [{ age: { $gt: 30 } }, { gender: "female" }] })
b. Execute the Commands of MongoDB and operations in MongoDB:
Insert, Query, Update, Delete and Projection.
// Insert document
db.collection.insertOne({ name: "John", age: 35, gender: "male" })
// Query document
db.collection.find({ age: { $gt: 30 } })
// Update document
db.collection.updateOne({ name: "John" }, { $set: { age: 40 } })
// Delete document
db.collection.deleteOne({ name: "John" })
// Projection
db.collection.find({}, { name: 1, age: 1 })
Experiment 2:
Aim: To understand use of limit and find
a. Develop a MongoDB query to select certain fields and ignore some fields
of the documents from any collection:
// Insert documents
// Select certain fields and ignore some fields
db.collection.find({}, { name: 1, age: 1, _id: 0 })
b. Develop a MongoDB query to display the first 5 documents from the
results obtained in a. [use of limit and find]:
// Display the first 5 documents
db.collection.find().limit(5)
Experiment 3:
a. Execute query selectors (comparison selectors, logical selectors) and
list out the results on any collection.
Aim: To understand different query selectors
// Insert documents
// Comparison selectors
db.collection.find({ age: { $gt: 30 } })
// Logical selectors
db.collection.find({ $and: [{ age: { $gt: 25 } }, { gender: "male" }] })
b. Execute query selectors (Geospatial selectors, Bitwise selectors) and
list out the results on any collection
// Create a geospatial index
// Geospatial selectors
db.collection.find({ location: { $near: { $geometry: { type: "Point", coordinates: [ -
73.9667, 40.78 ] }, $maxDistance: 5000 } } })
// For Bitwise selectors insert documents
db.collection.find({ status : { $bitsAllSet: [0,2] } })
Experiment 4:
Create and demonstrate how projection operators ($, $elematch and
$slice) would be used in the MongoDB.
Aim: To understand projection operators.
// Insert documents
// $ projection operator
db.collection.find({name: “Laptop”, “reviews.user”: “Alice”}, { "reviews.$": 1 })
// $elemMatch projection operator
db.collection.find({name: “Laptop”}, { reviews: { $elemMatch: { rating: { $gt: 4 } }
} })
// $slice projection operator
db.collection.find({name:”Smartphone”}, { revie: { $slice: 1 } })
Experiment 5:
Execute Aggregation operations ($avg, $min, $max, $push, $addToSet
etc.) students encourage to execute several queries to demonstrate
various aggregation operators)
Aim: To understand Aggregation operations.
// Insert documents
// $avg
db.collection.aggregate([{ $group: { _id: “$product”, averagePrice: { $avg: "$price" }
} }])
// $min
db.collection.aggregate([{ $group: { _id: “$product”, minPrice: { $min: "$price" } }
}])
// $max
db.collection.aggregate([{ $group: { _id:”$product”, maxPrice: { $max: "$price" } }
}])
// $push
db.collection.aggregate([{ $group: { _id: “$customer”, products: { $push: "$product"
} } }])
// $addToSet
db.collection.aggregate([{ $group: { _id: “$customer”, uniqueProducts: { $addToSet:
"$product" } } }])
Example: Calculate the total quantity and total sales amount for each product and list all
customers who purchased each product.
Expected Result:
Experiment 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).
Aim: To understand Pipeline and its operations.
// Insert documents
// Aggregation Pipeline syntax:
db.collection.aggregate([
{ $match: { location: “Jayanagar”}},
{ $group: { _id: "$name", averageRating: { $avg: “$reviews.rating”}, totalReviews: {
$sum: 1 } } },
{ $sort: { averageRating: -1 } },
{ $skip: 1 },
{ $project: { _id: 0, restaurant: "$_id", averageRating: 1, totalReviews:1} }
])
Expected Results:
Experiment 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.
Aim: To understand all listings.
db.listingsAndReviews.find({“host.picture_url”:{$exists:true,$ne:“”}},
{listing_url:1, name: 1, address: 1, “host_picture_url”: 1})
Expected Result:
b. Using E-commerce collection write a query to display reviews
summary.
// Insert documents
db.products.aggregate([{$group:{_id:"$name",averageRating:{$avg:
"$reviews.rating"},comments:{$push:”reviews.comments”}totalReviews: { $sum:
1 } } } ])
Expected Result:
Experiment 8:
a. Demonstrate creation of different types of indexes on collection
(unique, sparse, compound and multikey indexes)
Aim: To understand different types of collection using index.
// Insert documents
// Unique index
db.collection.createIndex({ username: 1 }, { unique: true })
// Sparse index
db.collection.createIndex({ city: 1 }, { sparse: true })
// Compound index
db.collection.createIndex({ name: 1, city: 1 })
// Multikey index
db.collection.createIndex({ reviews: 1 })
// Verify the created indexes
Expected Result:
b. Demonstrate optimization of queries using indexes.
// Creating Indexes
// Create a compound index on 'customerId' and 'orderDate’
x
Experiment 9:
a. Develop a query to demonstrate Text search using catalog data
collection for a given word.
Aim: To understand text search using collection for a given word.
// Insert documents
//Create a Text Index
// db.catalog.find({ $text: { $search: "keyword" } })
b. Develop queries to illustrate excluding documents with certain
words and phrases
// Exclude Documents Containing a Single Word
// Exclude Documents Containing Multiple Words
//Exclude Documents Containing a Specific Phrase
// Exclude Documents Containing Any of Multiple Phrases
// Exclude Documents with Case-Insensitive Word
//Exclude Documents Where a Specific Field Contains a Value
// Exclude Documents with Words or Phrases and Include Additional Conditions
// Exclude Documents Where the Field Contains a Number.
// Exclude Documents Using an Array of Phrases.
Experiment 10:
Develop an aggregation pipeline to illustrate Text search on Catalog
data collection.
Aim: To understand aggregation pipeline operations using text search on catalog data.
// Insert documents
// Create a Text Index
// Run the Aggregation Pipeline
db.Catalog.aggregate([{ $search: { index: 'default', // The name of the search index to
use text: { query: 'your_search_query_here', // The text to search for path: 'description'
// The field in the documents to search } } }, { $project: { _id: 0, // Exclude the _id
field from the output productName: 1, // Include the productName field in the output
description: 1, // Include the description field in the output score: { $meta:
'searchScore' } // Include the search score in the output } } ])
Expected Result:
Viva Questions
Q1. Define MongoDB?
Ans. MongoDB is a popular open-source, NoSQL (non-relational) database management
system that is created to store, retrieve, and manage data flexible and scalable. MongoDB is
classified as a document database, storing data in a format similar to JSON (JavaScript Object
Notation) documents.
Q2. How does MongoDB differ from traditional relational databases?
Ans. MongoDB is a NoSQL database, while traditional relational databases are SQL-based. It
stores data in flexible, schema-less documents, whereas relational databases use structured
tables with fixed schemas.
Q3. Can you explain what a document in MongoDB is?
Ans. A document is a JSON-like data structure that stores and represents data. It can contain
key-value pairs, arrays, and nested documents. Documents are stored in collections, equivalent
to tables in relational databases.
Q4. What is a collection in MongoDB?
Ans. A collection in MongoDB is a grouping of documents.
Q5. How does MongoDB store data?
Ans. MongoDB stores data in BSON (Binary JSON) format, a binary-encoded serialization of
JSON-like documents. These documents are stored in collections within databases.
Q6. What is a primary key in MongoDB?
Ans. In MongoDB, the `_id` field serves as the primary key for a document. It must be unique
within a collection and is automatically generated if not provided during document insertion.
Q7. What are indexes in MongoDB?
Ans. MongoDB employs data structures known as indexes to enhance query performance,
enabling the database to swiftly locate documents according to the indexed fields. MongoDB
offers support for a range of index types.
Q8. How do you create a database in MongoDB?
Ans. You create a database implicitly by switching to it or explicitly by running the `use
<database_name>` command in the MongoDB shell. When you insert data into it, MongoDB
will create the database if it doesn't already exist.
Q9. How do you insert data into a MongoDB collection?
Ans. We can insert data into a MongoDB collection using the `insertOne()` or `insertMany()`
method. You provide a document or an array of documents to be inserted.
Q10. What are the data types supported by MongoDB?
Ans. MongoDB supports various data types, including string, number, boolean, date, array,
object, null, regex, and more. It also helps geospatial and binary data types.
Q11. How do you update documents in MongoDB?
Ans. We can update documents in MongoDB using methods like `updateOne()`,
`updateMany(),` or `findOneAndUpdate().` You specify the query to select the documents to
update and provide an update operation.
Q12. What is the role of `_id` in MongoDB documents?
Ans. The `_id` field uniquely identifies each document in a collection. MongoDB uses it as the
primary key, and if not provided during document insertion, MongoDB generates a unique
value for it.
Q13. How do you delete data from a MongoDB collection?
Ans. We can delete data from a MongoDB collection using methods like `deleteOne()`,
`deleteMany()`, or `findOneAndDelete()`. You specify a query to select the documents to
delete.
Q14. What is a cursor in MongoDB, and when is it used?
Ans. A cursor in MongoDB is an iterator to retrieve and process documents from query results.
Cursors are used when fetching large result sets, allowing you to retrieve documents in batches.
Q15. What is the role of collections in MongoDB?
Ans. Collections in MongoDB are containers for organizing and storing related documents.
They act as the equivalent of tables in relational databases, grouping similar data.
Q16. How do you perform a query in MongoDB?
Ans. You can perform queries in MongoDB using the `find()` method, where you specify
criteria to filter documents. You can also use various query operators to refine your queries.
Q17. Explain the concept of aggregation in MongoDB?
Ans. MongoDB's aggregation framework is a powerful tool designed for processing and
transforming documents within a collection. With it, you can execute various operations such
as grouping, sorting, and computing aggregate values on your dataset.
Q18. What are the main features of MongoDB?
Ans. Some prominent features of MongoDB include flexibility in data modelling, horizontal
scalability, support for unstructured data, powerful query language, automatic sharding, high
availability with replica sets, and geospatial capabilities.
Q19. What is the Mongo Shell?
Ans. It is a JavaScript shell that allows interaction with a MongoDB instance from the
command line.
Q20. What are Databases in MongoDB?
Ans. MongoDB groups collections into databases. MongoDB can host several databases, each
grouping together collections. Some reserved database names are as follows: admin, local,
config.
Q21. Explain the SET Modifier in MongoDB?
Ans. If the value of a field does not yet exist, the "$set" sets the value. This can be useful for
updating schemas or adding user-defined keys.
Q22. What are Geospatial Indexes in MongoDB?
Ans. MongoDB has two types of geospatial indexes: 2dsphere and 2d. 2dsphere allows you to
specify geometries for points, lines, and polygons in the GeoJSON format. A point is given by
a two-element array, representing [longitude, latitude]: Use 2d indexes for points stored on a
two-dimensional plane.
Q23. Explain the concept of pipeline in the MongoDB aggregation framework.
Ans. An individual stage of an aggregation pipeline is a data processing unit. It takes in a stream
of input documents one at a time, processes each document one at a time, and produces an
output stream of documents one at a time.
Q24. What is the purpose of using $group?
Ans. $group syntax is used to bundle or group the documents of a collection based on one or
more fields.
Q25. What is the difference between the find() and limit() methods?
Ans. find(): displays only selected data rather than all the data of a document. For example, if
your document has 10 fields but you want to show only five, set the required field as 5 and
others as 0.
limit(): limit function limits the number of records fetched. For example, if you have 10
documents but want to display only the first 5 documents in a collection, use the limit.