0% found this document useful (0 votes)
54 views145 pages

Wa0005.

The document provides an overview of MongoDB, an open-source, document-oriented NoSQL database management system, highlighting its components, structure, and functionalities. It contrasts MongoDB with traditional SQL databases, emphasizing its flexibility and suitability for dynamic data models. Additionally, it covers various operations such as CRUD, query operators, projections, and geospatial queries, along with examples of their usage.

Uploaded by

UNNATI SAXENA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
54 views145 pages

Wa0005.

The document provides an overview of MongoDB, an open-source, document-oriented NoSQL database management system, highlighting its components, structure, and functionalities. It contrasts MongoDB with traditional SQL databases, emphasizing its flexibility and suitability for dynamic data models. Additionally, it covers various operations such as CRUD, query operators, projections, and geospatial queries, along with examples of their usage.

Uploaded by

UNNATI SAXENA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 145

MongoDB

Presented By:
GEENA GEORGE
Asst. Prof. CSE
Introduction
• A database is a structured collection of data that is organized and stored in a computer system. Databases

are used in a wide range of applications, including websites, business applications, scientific research etc.

• MongoDB is a open source, document-oriented NoSQL database management system.

• A document database(also known as a document-oriented database or document store) is a database that

stores information in document.

• Designed for flexibility, scalability, and performance in handling structured and un-structured data.
Contd..
• It was developed by MongoDB Inc.

• Initially released in 2009.

• Written in C++, C, and .


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 They provide flexibility in data storage,
in rows and columns allowing varied data types and structures.

Suitable for applications with well Ideal for application with dynamic or
defined schemas and fixed data evolving data models
structured
E-commerce platform, HR CMS, Social media platform, Gaming
management platform
Ex: MySQL, Oracle, PostgreSQL Ex: MongoDB, Cassandra, Redis
MongoDB Database structure
MongoDB Terminology
MongoDB Compass
Create Database
Contd..
Difference
How mongoDB works

Wired Tiger
Back End Or
Frond End Database MMAPV1

Read and Write


Data Files
Basic Queries
1. show dbs;

2. use database name;

3. db.dropDatabase();

4. show collections;

5. db.createCollection(‘Collection Name’);

6. db.collectionname.drop();

7. db.collectionname.find();
CRUD Operations
Insert One Insert many
db.collectionname.insertOne({ db.collectionname.insertOne([{
field1:value1, field1:value1,
field2:value2, field2:value2……},
…………. {
}) field1:value1,
field2:value2……},
//………..])
When to use quotes and when not to use
• Special Character:
• If a field name contains special character, starts with numeric or space, using
quote is necessary.

• Reserved Character:
• If field name is reserved keyword in MongoDB, use quotes distinguished it
from the reserved keywords.
Ordered and Unordered insert
 When executing the bulk operations, “Ordered and “Unordered” will determine the batch behaviour.
• Ordered inserts:

• By Default, documents are inserted in the given order.

db.collectionname.insertMany([{key:values},…..])
• Unordered inserts:

• when executing bulk write operations with unordered flag MongoDB processing after

encountering the error,

• if you want to insert documents in unordered, then set the value of ordered to false
db.collectionname.insertMany([{key:values},…..],{ordered : false})
Case Sensitivity in MongoDB
• Collection names are case sensitive.
• Field name within document are also case sensitive.
db.Product.insertOne(name : ‘XYZ’, price : 123)
db.product.insertOne(name : ‘XYZ’, price : 123)
Read Operation
• find(): The find() method retrieves documents from a collection.
1. db.collectionName.find()->>>>>for all the data in that collection.
2. db.collectionName.find({key : value})->>>>>> for specific set of
data as per the matching condition.
3. db.collectionName.findOne({key : value})->>>>>>for specific One
data as per the matching condition.
Comparision Operator
• $eq: Equal to, db.collectionName.find({fieldna
• $ne: not Equal to, me:{$operator: Value}})
• $gt:Greater than, • db.products.find({‘Price’:{$gte:
• $lt: Less than, 18000}})
• $gte: Greater than equal to,
• $lte: Less than equal to,
• $in: in: to select documents where the
• db.products.find({ Price:{$in:
value of a field equal to any values in the [235,567,876]}})
specified array.
• $nin: not in: to select documents where
the value of a field is not equal to any .count(), .limit()
values in an array.
Logical Operator

• $and: It performs a logical AND operation on an array of expression , where all expression
must be true for the document to match.

• Joins two or more queries with a logical AND returns the documents that match all the
conditions.

• $or: It performs a logical OR operation on an array of expression , atleast one expression


must be true for the document to match.

• Join two or more queries with a logical OR and return the documents that match either
query.
Logical Operator
1. $and • {$and : [{Condition1,
2. $or condition2,…..}]}
3. $nor
4. $not • {field: {$not : {operator :
value}}}
Complex Expression
• The $expr operator allows using aggregation expressions within a query.

• Useful when you need to compare the fields from the same documents in more
complex manner.
Syntax:
{$expr : {Operator: [field : value]}}
Example :
db.College_books.find({$expr : {$gt: [‘_id’ : 15]}} )
Projections
db.collection.find({‘field : value}, {field1: 1 , field2 : 0})

• It is a special feature allowing you to select only the necessary data rather than selecting
the whole set of data from the document.

• For Example: If a Document contains 10 fields and only 5 fields are to be shown the
same can be achieved using the projections.

• To include specific fields , use projection with value of 1 for the field you want.

• To exclude specific fields , use projection with value of 0 for the field you want.

• You cannot include and exclude fields simultaneously in the same query projection.
Example: db.mycol.find({},{‘title’=1,_id = 0})
Update Operations
• UpdateOne()

• UpdateMany()

• Removing and renaming fields.


UpdateOne and Updatemany syntax
• db.collection.updateOne(
{filter}, {$set : {existingfield : new value , newField : new
Value}})
db.students.updateOne( { _id: 9 }, { $set: { name : 'Amar'} })

• db.collection.updateMany(
{filter}, {$set : {existingfield : new value //,}})
db.students.updateMany( { _id: {$lt: {_id : 3}} }, { $set: { name:
"Patil"}})
Removing and Renaming
• db.collection.updateOne(

{filter}, {$unset : {existingfield : 1}})

• db.collection.updateOne(

{filter}, {$rename : {existingfield : new value}})


Delete Operation
• DeleteOne():
db.document.deleteOne({key : value})
• DeleteMany():
db.document.deleteMany({key : value})
Lab Program 1(b)
Contd..
Contd..
Contd..
Contd..
Lab Program 1(a)
Contd..
Contd..
Contd..
Introduction to the MongoDB $and operator
• The $and is a logical query operator that allows you to carry a logical AND operation on
an array of one or more expressions.

• The $and operator returns true if all expressions evaluate to true.

• The following shows the syntax of the $and operator:

• When you use a comma-separated list of expressions, MongoDB will carry an implicit
AND operation:
MongoDB $and operator examples
db.products.insertMany([

{ "_id" : 1, "name" : "xPhone", "price" : 799, "releaseDate" : ISODate("2011-05-14T00:00:00Z"), "spec" : { "ram" :


4, "screen" : 6.5, "cpu" : 2.66 }, "color" : [ "white", "black" ], "storage" : [ 64, 128, 256 ] },

{ "_id" : 2, "name" : "xTablet", "price" : 899, "releaseDate" : ISODate("2011-09-01T00:00:00Z"), "spec" : { "ram" :


16, "screen" : 9.5, "cpu" : 3.66 }, "color" : [ "white", "black", "purple" ], "storage" : [ 128, 256, 512 ] },

{ "_id" : 3, "name" : "SmartTablet", "price" : 899, "releaseDate" : ISODate("2015-01-14T00:00:00Z"), "spec" :


{ "ram" : 12, "screen" : 9.7, "cpu" : 3.66 }, "color" : [ "blue" ], "storage" : [ 16, 64, 128 ] },

{ "_id" : 4, "name" : "SmartPad", "price" : 699, "releaseDate" : ISODate("2020-05-14T00:00:00Z"), "spec" :


{ "ram" : 8, "screen" : 9.7, "cpu" : 1.66 }, "color" : [ "white", "orange", "gold", "gray" ], "storage" : [ 128, 256, 1024 ] },

{ "_id" : 5, "name" : "SmartPhone", "price" : 599, "releaseDate" : ISODate("2022-09-14T00:00:00Z"), "spec" :


{ "ram" : 4, "screen" : 9.7, "cpu" : 1.66 }, "color" : [ "white", "orange", "gold", "gray" ], "storage" : [ 128, 256 ] },

{ "_id" : 6, "name" : "xWidget", "spec" : { "ram" : 64, "screen" : 9.7, "cpu" : 3.66 }, "color" : [ "black" ], "storage" :
[ 1024 ] }

])
1) Using MongoDB $and operator example
• The following example uses the $and operator to select all documents in the products
collection where:
• the value in the price field is equal to 899 and
• the value in the color field is either "white" or "black“ Output:
MongoDB $or Operator
• The $or operator performs logical "OR operations" on an array of one or more
expressions. This operator is only used to retrieve the documents that match at least one
of the given expressions in the array.

• Syntax:
Contd..
Contd..
Contd..
• In this example, we are only retrieving the data of students whose Course is "MCA" or
batch_year is 2018.
>db.student.find({$or: [{Course : "MCA"}, {batch_year : 2018}]}).pretty()
Output:
Contd..
Contd
• In this example, we are only retrieving those student's documents whose City is "London"
or age is 20.
>db.student.find({$or: [{"personal.age": 20}, {"personal.City": "London"}]}).pretty()
Output:
Contd..
Query Operators:
• Projection: The projection parameter in find() allows you to specify which fields to include or
exclude in the result set.

• db.collection_name.find({ key: value }, { field1: 1, field2: 1, ... })

• Example: db.users.find({}, { name: 1, age: 1 }) retrieves only the name and age fields from the
users collection.
• MongoDB provides various query operators for complex queries:

o Comparison Operators ($eq, $gt, $lt, etc.):

o Example: db.users.find({ age: { $gt: 25, $lt: 40 } }) retrieves users with ages between 25 and 40.

o Logical Operators ($and, $or, $not, $nor)

o Element Operators ($exists, $type)

o Array Operators ($in, $all, $elemMatch)


Contd..
• Limiting Results: The limit() method limits the number of documents returned in the
result set.

• db.collection_name.find().limit(number)

• Example: db.users.find().limit(10) retrieves the first 10 users.

• Skipping Results: The skip() method skips a specified number of documents and returns
the rest.

• db.collection_name.find().skip(number)

• Example: db.users.find().skip(5) skips the first 5 users.


Contd..
Experiment 2:
a. Develop a MongoDB query to select certain fields and ignore some fields of
the 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:

// Display the first 5 documents

db.collection.find().limit(5)
Contd..
Contd..
Contd..
2b. Develop a MongoDB query to display the first 5 documents:
Contd..

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


some fields of the documents:
Contd..
• Following is the query to skip first 5 records and display only the last 5 of
them − > db.Employee.find().skip(5).limit(5)
Contd..
• Experiment 3(a):
Execute query selectors (comparison selectors, logical selectors):

// Comparison selectors

db.collection.find({ age: { $gt: 30 } })

// Logical selectors

db.collection.find({ $and: [{ age: { $gt: 25 } }, { gender: "male" }] })


Contd..
Experiement 3(a) (contd..)
// Comparison selectors
db.collection.find({ age: { $gt: 30 } })
Contd..
// Logical selectors
db.collection.find({ $and: [{ age: { $gt: 25 } }, { gender: "male" }] })
Contd..
Experiment 3(b):

Execute query selectors (Geospatial selectors):

• MongoDB supports geospatial queries for location-based data.

// Geospatial selectors

db.collection.find({ location: { $near: { $geometry: { type: "Point", coordinates: [ -


73.9667, 40.78 ] }, $maxDistance: 1000 } } })

Try by yourself:

db.collection.find({ location: { $near: { $geometry: { type: "Point", coordinates: [ -


73.9851, 40.7580 ] }, $maxDistance: 5000 } } })
Contd..
Geospatial Queries(Contd..)
1. $near (Find places near a certain point)

Specifies a point for which a geospatial query returns the documents from nearest to farthest.

$near requires a geospatial index:

2dsphere index if specifying a GeoJSON point,

2d index if specifying a point using legacy coordinates.

To specify a GeoJSON point, $near operator requires a 2dsphere index and has the following syntax:
Contd..
• If specifying latitude and longitude coordinates, list the longitude first and then latitude:
o Valid longitude values are between -180 and 180, both inclusive.
o Valid latitude values are between -90 and 90, both inclusive.

• When specifying a GeoJSON point, you can use the optional $minDistance and $maxDistance
specifications to limit the $near results by distance in meters:

o $minDistance limits the results to those documents that are at least the specified distance from the
center point.

o $maxDistance limits the results to those documents that are at most the specified distance from the
center point.

• To specify a point using legacy coordinates, $near requires a 2d index and has the following
syntax:
Contd..
• First, let’s create a Places collection with geospatial data.
• Create the Places Collection and Insert Documents.
// Create a geospatial index
db.Places.createIndex({ location: "2dsphere" })
Contd..
// Geospatial selectors
db.collection.find({ location: { $near: { $geometry: { type: "Point",
coordinates: [ -73.9667, 40.78 ] }, $maxDistance: 1000 } } })
Contd..
Find places near a specific coordinate, for example, near Times Square.
Bitwise Selectors
Contd..
// Bitwise selectors
Let’s create a Devices collection for bitwise operations.
Create the Devices Collection and Insert Documents.
Contd..
Execute Bitwise Queries
$bitsAllSet (Find documents where all bits are set)
Find devices where the binary status has both the 1st and 3rd bits set (binary mask 0101, or
decimal 5).
Contd..
Experiment 4:
Create and demonstrate how projection operators would be used:
To demonstrate the use of projection operators ($, $elemMatch, and $slice) in MongoDB, let’s create
a Products collection. We’ll insert documents that include arrays, which will allow us to showcase
these operators effectively.

Create the Products Collection and Insert Documents


Contd..
Contd..
Use Projection Operators:
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.collection.find( { name: "Laptop”, reviews.user”: “Alice” }, { “reviews.$”:1})


Contd..
// $elemMatch projection operator:
The $elemMatch operator is used to project the first matching element from an array based on
specified criteria.
Example: Find the product named “Laptop” and project the review where the rating is greater
than 4.
db.collection.find({ name: "Laptop" },{ reviews: { $elemMatch: { rating: { $gt: 4 } } } })
Contd..
// $slice projection operator:
The $slice operator is used to include a subset of the array field, such as the first n elements
or a specific range.
Example: Find the product named “Smartphone” and project the first review.
db.collection.find( { name: "Smartphone" }, { reviews: { $slice: 1 } })
Contd..
Experiment 5:
Execute Aggregation operations:
• MongoDB's aggregation framework allows you to perform advanced data processing
operations.

• It allow you to group, sort, perform calculations, analyze data, and much more.

• 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.
Contd..
Create the Sales Collection and Insert Documents.
First, we’ll create the Sales collection and insert sample documents.
Execute Aggregation Operations
1. $avg (Average): To calculate the average price of each product.
Contd..
2. $min (Minimum): To find the minimum price of each product.
Contd..
3. $max (Maximum): To find the maximum price of each product.
Contd..
4.$push(Push Values to an Array): Group sales by customer and push each purchased
product into an array.
Contd..
5.$addToSet(Add Unique Values to an Array): Group sales by customer and add
each unique purchased product to an array.
Combining Aggregation Operations
• Example: Calculate the total quantity and total sales amount for each product, and
list all customers who purchased each product.
Contd..
Contd..
• Note: By using aggregation operations such as $avg, $min, $max, $push, and $addToSet,
you can perform complex data analysis and transformations on MongoDB collections.
These operations enable you to calculate averages, find minimum and maximum values,
push values into arrays, and create sets of unique values. The examples provided show
how to use these operators to analyze a Sales collection.
Contd..
Lab Program 6:
Aggregation Pipeline and its operations
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)
Contd..
• 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.

• Now, let’s execute an aggregation pipeline that includes the $match, $unwind, $group,
$sort, $project, and $skip stages.
Contd..
Contd..
Contd..
// Run the aggregation pipeline query to display reviews summary.
Contd..
Result:
Contd..
Aggregation Pipeline Explanation:

1. $match: Filter restaurants by cuisine ("Jayanagar" location).

2. $unwind: Deconstruct the reviews array from each document to output a document for each
review. I.e., create separate output documents for each item in the array.

3. $group: Group the documents by restaurant name and calculate the average rating and total
number of reviews.

4. $sort: Sort the results by average rating in ascending order[-1], descending order[1]

5. $project: Restructure the output to include only the restaurant name, average rating, and
total reviews.

6. $skip: Skip the first document.


Contd..
Lab Program 7(a):
To find all listings with listing_url, name, address, and host_picture_url in the listings And Reviews
collection where the host has a picture URL, let is create appropriate databases and queries as
follows.

Create the Database: ‘vacationRentals’

First, switch to or create the database you want to use. For this example, let’s call the database
vacationRentals.
Contd..
Create the listings And Reviews Collection and Insert Documents
Next, create the listingsAndReviews collection and insert sample documents. Here are a few example
documents to illustrate the structure:
Contd..
Contd..
Query to Find Listings with Host Picture URLs:

Now that the collection is set up, you can run the query to find all listings with listing_url,
name, address, and host_picture_url where the host has a picture URL.
Expected Result
• The query should return documents where the host has a picture URL. Based on the inserted documents,
the result should look something like this:
Contd..
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.
Contd..
Lab Program 7(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.
Contd..
Contd..
Contd..
Sample Output:
• The query will return a summary for each product in the collection.
Contd..
Explanation:
1. $unwind: Deconstructs the reviews array from each document to output a document for each
element.
2. $group: Groups the documents by product name, and calculates:
• totalReviews: The total number of reviews for each product.
• averageRating: The average rating of the reviews for each product.
• comments: An array of all review comments for each product.

3. $project: Restructures the output documents to include the product name, total reviews,
average rating, and comments.
Contd..
Lab Program 8(a):
Demonstrate creation of different types of indexes on collection (unique, sparse,
compound and multikey indexes).

Let’s demonstrate the creation of various types of indexes on a restaurants collection in the
restaurantDB database. We’ll cover unique, sparse, compound, and multikey indexes.

Step 1: Create the Database and Collection

First, let’s set up the restaurantDB database and insert sample documents into the
restaurants collection.
Contd..
// Switch to the restaurantDB database
use restaurantDB
// Insert sample documents into the restaurants collection
db.restaurants.insertMany([n {n name: u0022Biryani Houseu0022,n cuisine: u0022Indianu0022,n location:
u0022Downtownu0022,n reviews: [n { user: u0022Aaravu0022, rating: 5, comment: u0022Amazing biryani!u0022 },n{ user:
u0022Bhavanau0022, rating: 4, comment: u0022Great place!u0022}n],n contact:
{phone:u00221234567890u0022,email:[email protected] }n },n {n name: u0022Curry Palaceu0022,n
cuisine: u0022Indianu0022,n location: u0022Downtownu0022,n reviews: [n { user: u0022Gauravu0022, rating: 4, comment:
u0022Spicy and tasty!u0022 },n { user: u0022Hariniu0022, rating: 5, comment: u0022Best curry in town!u0022 }n ],n contact: {
phone: u00220987654321u0022, email: [email protected] }n },n {n name: u0022Taco Standu0022,n cuisine:
u0022Mexicanu0022,nlocation: u0022Downtownu0022,n reviews: [n{ user: u0022Ishaanu0022, rating: 5, comment:
u0022Fantastic tacos!u0022 },n { user: u0022Jayau0022, rating: 4, comment: u0022Very authenticu0022 }n ],n contact:
{ phone: u00221122334455u0022, email: [email protected] }n }n])
Contd..
Step 2: Create Various Indexes

1. Unique Index: A unique index ensures that the indexed field does not contain
duplicate values. //Create a unique index on the contact.email field

2. Sparse Index: A sparse index only includes documents that contain the indexed
field, ignoring documents where the field is missing. // Create a sparse index on the
location field.
Contd..
3. Compound Index:A compound index indexes multiple fields within a single index.
// Create a compound index on the name and location fields

4. MultikeyIndex: A multikey index is created on an array field, indexing each element


of the array.
// Create a multikey index on the reviews fields
Contd..
Step 3: Verify Indexes
To verify the created indexes, you can use the getIndexes method.
// Verify the created indexes

Output:
Contd..

• This script sets up the restaurantDB database, populates the restaurants collection
with sample data, and demonstrates the creation of unique, sparse, compound, and
multikey indexes. The getIndexes method at the end allows you to verify the
indexes created on the collection.
Contd..

Lab Program 8(b):


• Demonstrate optimization of queries using indexes.

Step1: Creating Indexes

To create indexes, use the createIndex method.


Contd..
Single Field Index:
// Connect to your MongoDB instance using the shell
use yourDatabase; // switch to your database

// Create an index on the 'customerId' field


db.orders.createIndex({ customerId: 1 });
Contd..
Compound Index:
// Create a compound index on 'customerId' and 'orderDate’

2. Analyzing Query Plans:


Use the explain method to analyze how your queries use indexes.
a. Explain for a Find Query by customerId
// Run the query with explain

Check the executionStats for details such as indexName and totalKeysExamined to confirm
that the index is being used.
Contd..
Contd..
Contd..
b. Explain for a Date Range Query:
Contd..
Contd..
c. Explain for an Aggregation Query
// Run the aggregation query with explain
db.orders.aggregate([ { $match: { customerId: 123 } }, { $group: { _id:
"$customerId", totalAmount: { $sum: "$amount" } } }]).explain("executionStats");
Check if the $match stage benefits from the customerId index.
3. Managing Indexes
List Existing Indexes: db.orders.getIndexes();
Contd..

Drop an Index:
// Drop an index (specify the index name or key pattern)
Contd..

• MongoDB Compass offers a graphical way to create and manage indexes and analyze query plans,
making it easier for users who prefer a visual interface. MongoDB Shell provides command-line
flexibility for creating indexes, analyzing query performance with explain, and managing indexes
directly through commands. Both methods are effective, and your choice between them may
depend on your preferences and the specific requirements of your work environment.
Contd..
Lab 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, let’s study through a complete
example, including creating a collection, inserting sample data, creating a text index, and performing
a text search query.

Step1: Set Up the Collection and Insert Sample Data

First, you need to set up a MongoDB collection named catalog and insert some sample
documents. Here’s how you can do that:
Contd..
Contd..
Step2: Create a Text Index
To enable text search on the description field, create a text index on it.

Step3: Perform a Text Search

Now you can perform a text search query to find documents that contain the word "laptop"
in the description field:
Contd..
Step4: Include a Text Score (Optional)
To rank the results based on their relevance to the search term, you can include a text score in your
query and sort by it:
Example Output: Based on the sample data, running the text search query would return documents
where the description contains the word "laptop“In this output, documents with "laptop" in the
description field are returned. The score field indicates the relevance of the document to the search
term.
Contd..
Summary:
1. Insert sample data into the catalog collection.

2. Create a text index on the description field.

3. Run a text search query to find relevant documents.

4. Optionally include a text score to sort results by relevance.


Contd..

Lab Program 9(b):

Develop queries to illustrate excluding documents with certain words and phrases

• Certainly! Below are various MongoDB queries illustrating how to exclude documents containing
certain words or phrases. These examples assume that the collection is named documents and the
field being searched is content.

Step1: Exclude Documents Containing a Single Word

To exclude documents that contain the word "marketing” in the content field
Contd..
Step2:Exclude Documents Containing Multiple Words
To exclude documents that contain either "AI" or "robotics“

Step3: Exclude Documents Containing a Specific Phrase


To exclude documents where the content field contains the exact phrase "global warming"
Contd..
Step4: Exclude Documents Containing Any of Multiple Phrases
To exclude documents containing any of the phrases "global warming" or "climate change"

Step5: Exclude Documents with Case-Insensitive Word


To exclude documents where the content field contains the word "marketing" regardless of
case.
Contd..
Step6: Exclude Documents Where a Specific Field Contains a Value
To exclude documents where the category field is "science“

Step7: Exclude Documents with Words or Phrases and Include Additional Conditions
To find documents that contain "data analysis" but exclude those mentioning "marketing"
or "AI“
Contd..
Step8: Exclude Documents Containing Any Word from an Array
To exclude documents containing any word from the array ["AI", "robotics", "machine
learning"]

Step9: Exclude Documents Where a Field Starts or Ends with Specific Phrases
To exclude documents where the content field starts with "Introduction" or ends with
"Conclusion“
Contd..
Step10: Exclude Documents Based on Partial Matches
To exclude documents containing any part of the phrase "data privacy”

Step11: Exclude Documents Where Multiple Fields Contain Certain Words


To exclude documents where either the content field or the description field contains the
word "confidential“
Contd..
Step12: Exclude Documents Based on Regular Expression with Multiple Words.
To exclude documents that contain any of the words "confidential", "private", or "restricted“

Step13:Exclude Documents Where the Field Contains a Number.


To exclude documents where the score field contains the number 100.
Contd..
Step14: Exclude Documents Using an Array of Phrases.
To exclude documents containing any of the phrases ["confidential data", "restricted
access"]

Explanation of Key Components:


$not Operator: This is used with regular expressions to exclude documents where a field matches
the specified pattern.
$and Operator: Combines multiple conditions to ensure all specified conditions must be met for
exclusion.
Regular Expressions: Allow flexible pattern matching to find words or phrases in documents.
Case Insensitivity: The i flag in regular expressions makes the search case-insensitive.
Contd..
Lab 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.
Contd..
• Let’s create an aggregation pipeline that includes various stages:

1. $match: Filters documents that match the text search query. Here it filters documents
that match the text search query "MongoDB"

2. $addFields: Adds a score field to each document containing the relevance score of the
text search, which is computed by MongoDB..

3. $sort: Sorts the documents by the ‘score’ field in descending order to prioritize more
relevant results.

4. $project: Specifies which fields to include in the final output. Here, title, description,
and score are included.
Contd..
Here’s a step-by-step guide to perform a text search on a catalog data collection using the
aggregation pipeline:
Step1: Connect to MongoDB
Open your terminal and connect to your MongoDB instance. mongosh
Step2: Create the catalog Collection

Create a sample catalog collection with some documents. You can use the following
commands to insert documents into the collection:
Contd..
Contd..
Step3: Create a Text Index
Create a text index on the title and description fields of the catalog collection.

Step4: Run the Aggregation Pipeline


Use the following aggregation pipeline to perform a text search and sort the results by
relevance:
Contd..
Example Execution:
Here’s a complete example of what you would type in the MongoDB terminal:

You might also like