1.
Illustration of Where Clause, AND,OR operations in
[Link] : Insert, Query, Update, Delete and
Projection.
Switch to created DB:
use ProgBooksDB
switched to db ProgBooksDB
Create Collection:
ProgBooksDB> [Link]("ProgrammingBooks")
Insert One Documents:
ProgBooksDB> [Link]({
title: "The Pragmatic Programmer: Your Journey to Mastery",
author: "David Thomas, Andrew Hunt",
category: "Software Development",
year: 1999
})
Insert Many Documents:
ProgBooksDB> [Link]([
{
title: "Clean Code: A Handbook of Agile Software Craftsmanship",
author: "Robert C. Martin",
category: "Software Development",
year: 2008
},
{
title: "JavaScript: The Good Parts",
author: "Douglas Crockford",
category: "JavaScript",
year: 2008
},
{
title: "Design Patterns: Elements of Reusable Object-Oriented Software",
author: "Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides",
category: "Software Design",
year: 1994
},
{
title: "Introduction to Algorithms",
author: "Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein",
category: "Algorithms",
year: 1990
},
{
title: "Python Crash Course: A Hands-On, Project-Based Introduction to
Programming",
author: "Eric Matthes",
category: "Python",
year: 2015
}
])
Find Documents:
ProgBooksDB> [Link]().pretty()
[
{
_id: ObjectId('664ee3b1924a8039f62202d8'),
title: 'The Pragmatic Programmer: Your Journey to Mastery',
author: 'David Thomas, Andrew Hunt',
category: 'Software Development',
year: 1999
},
{
_id: ObjectId('664ee452924a8039f62202d9'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin',
category: 'Software Development',
year: 2008
},
{
_id: ObjectId('664ee452924a8039f62202da'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
},
{
_id: ObjectId('664ee452924a8039f62202db'),
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
author: 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides',
category: 'Software Design',
year: 1994
},
{
_id: ObjectId('664ee452924a8039f62202dc'),
title: 'Introduction to Algorithms',
author: 'Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein',
category: 'Algorithms',
year: 1990
},
{
_id: ObjectId('664ee452924a8039f62202dd'),
title: 'Python Crash Course: A Hands-On, Project-Based Introduction to
Programming',
author: 'Eric Matthes',
category: 'Python',
year: 2015
}
]
Where Clause(Find The Documents with condition):
ProgBooksDB> [Link]({ year: { $gt: 2000 } }).pretty()
[
{
_id: ObjectId('664ee452924a8039f62202d9'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin',
category: 'Software Development',
year: 2008
},
{
_id: ObjectId('664ee452924a8039f62202da'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
},
{
_id: ObjectId('664ee452924a8039f62202dd'),
title: 'Python Crash Course: A Hands-On, Project-Based Introduction to
Programming',
author: 'Eric Matthes',
category: 'Python',
year: 2015
}
]
Update One Documents:
ProgBooksDB>[Link](
{ title: "Clean Code: A Handbook of Agile Software Craftsmanship" },
{ $set: { author: "Robert C. Martin (Uncle Bob)" } }
)
//verify by displaying books published in year 2008
ProgBooksDB> [Link]({ year: { $eq: 2008 } }).pretty()
[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin (Uncle Bob)',
category: 'Software Development',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e0'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'JavaScript',
year: 2008
}
]
//another way to verify
ProgBooksDB> [Link]({ author: { $regex: "Robert*" }
}).pretty()
[
{
_id: ObjectId('664ee452924a8039f62202d9'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin (Uncle Bob)',
category: 'Software Development',
year: 2008
}
]
Update Many Documents:
ProgBooksDB> [Link](
{ year: { $lt: 2010 } },
{ $set: { category: "Classic Programming Books" } }
)
//verify the update operation by displaying books published before year 2010
ProgBooksDB> [Link]({ year: { $lt: 2010 } }).pretty()
[
{
_id: ObjectId('663eaaebae582498972202df'),
title: 'Clean Code: A Handbook of Agile Software Craftsmanship',
author: 'Robert C. Martin (Uncle Bob)',
category: 'Classic Programming Books',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e0'),
title: 'JavaScript: The Good Parts',
author: 'Douglas Crockford',
category: 'Classic Programming Books',
year: 2008
},
{
_id: ObjectId('663eaaebae582498972202e1'),
title: 'Design Patterns: Elements of Reusable Object-Oriented Software',
author: 'Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides',
category: 'Classic Programming Books',
year: 1994
},
{
_id: ObjectId('663eaaebae582498972202e2'),
title: 'Introduction to Algorithms',
author: 'Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest,
Clifford Stein',
category: 'Classic Programming Books',
year: 1990
},
{
_id: ObjectId('663eab05ae582498972202e4'),
title: 'The Pragmatic Programmer: Your Journey to Mastery',
author: 'David Thomas, Andrew Hunt',
category: 'Classic Programming Books',
year: 1999
}
]
Delete operation Documents:
ProgBooksDB> [Link]({ title: "JavaScript: The Good
Parts" })
{ acknowledged: true, deletedCount: 1 }
//Verify to see document is deleted
ProgBooksDB> [Link]({ title: "JavaScript: The Good Parts"
}).pretty()
Experiment 2:
a. Select & ignore Fields
Create Database & Collection:
test> use MoviesDB
switched to db MoviesDB
MoviesDB> [Link]("Movies")
{ ok: 1 }
MoviesDB> [Link]([
{ title: "Inception", director: "Christopher Nolan", genre: "Science Fiction", year: 2010,
ratings: { imdb: 8.8, rottenTomatoes: 87 } },
{ title: "The Matrix", director: "Wachowskis", genre: "Science Fiction", year: 1999, ratings: {
imdb: 8.7, rottenTomatoes: 87 } },
{ title: "The Godfather", director: "Francis Ford Coppola", genre: "Crime", year: 1972,
ratings: { imdb: 9.2, rottenTomatoes: 97 } },
{ title: "Pulp Fiction", director: "Quentin Tarantino", genre: "Crime", year: 1994, ratings: {
imdb: 8.9, rottenTomatoes: 92 } },
{ title: "The Shawshank Redemption", director: "Frank Darabont", genre: "Drama", year:
1994, ratings: { imdb: 9.3, rottenTomatoes: 91 } },
{ title: "The Dark Knight", director: "Christopher Nolan", genre: "Action", year: 2008,
ratings: { imdb: 9.0, rottenTomatoes: 94 } },
{ title: "Fight Club", director: "David Fincher", genre: "Drama", year: 1999, ratings: { imdb:
8.8, rottenTomatoes: 79 } }
])
Including Specific Fields:
To include specific fields, set the fields you want to include to 1,
To select only the title and director fields from the Movies collection
MoviesDB> [Link]({}, { title: 1, director: 1 })
MoviesDB> [Link]({}, { title: 1, director: 1, _id: 0 })
Excluding Specific Field:
MoviesDB> [Link]({}, { ratings: 0 })
Combining Filter & Projection:
MoviesDB> [Link]({ director: "Christopher Nolan" }, { title: 1, year: 1, _id: 0 })
b. Use of Limit and find in MongoDB query
MoviesDB> [Link]({}, { title: 1, director: 1, year: 1, _id: 0 }).limit(5)
Experiment 3: Query selectors (comparison selectors, logical selectors )
test> use companyDB
companyDB> [Link]([
{ name: "Alice", age: 30, department: "HR", salary: 50000, joinDate: new Date("2015-01-15") },
{ name: "Bob", age: 24, department: "Engineering", salary: 70000, joinDate: new Date("2019-
03-10") },
{ name: "Charlie", age: 29, department: "Engineering", salary: 75000, joinDate: new
Date("2017-06-23") },
{ name: "David", age: 35, department: "Marketing", salary: 60000, joinDate: new Date("2014-
11-01") },
{ name: "Eve", age: 28, department: "Finance", salary: 80000, joinDate: new Date("2018-08-
19") }
])
a. Queries Using Comparison Selectors
1. $eq (Equal)
companyDB> [Link]({ department: { $eq: "Engineering" } }).pretty()
2. $ne (Not Equal)
companyDB> [Link]({ department: { $ne: "HR" } }).pretty()
3. $gt (Greater Than)
companyDB> [Link]({ age: { $gt: 30 } }).pretty()
4. $lt (Less Than)
companyDB> [Link]({ salary: { $lt: 70000 } }).pretty()
5. $gte (Greater Than or Equal)
companyDB> [Link]({ joinDate: { $gte: new Date("2018-01-01") } }).pretty()
6. $lte (Less Than or Equal)
companyDB> [Link]({ age: { $lte: 28 } }).pretty()
Queries Using Logical Selectors:
1. $and (Logical AND)
companyDB> [Link]({ $and: [{ department: "Engineering" }, { salary: { $gt: 70000 } } ]
}).pretty()
2. $or (Logical OR)
companyDB> [Link]({ $or: [ { department: "HR" }, { salary: { $lt: 60000 } } ] }).pretty()
3. $not (Logical NOT)
companyDB> [Link]({ department: { $not: { $eq: "Engineering" } } }).pretty()
4. $nor (Logical NOR)
companyDB> [Link]({ $nor: [ { department: "HR" }, { salary: { $gt: 75000 } } ]
).pretty()
b. Query selectors (Geospatial selectors, Bitwise selectors)
Geospatial Selectors:
test> use geoDatabase
switched to db geoDatabase
geoDatabase> [Link]([
{ name: "Central Park", location: { type: "Point", coordinates: [-73.9654, 40.7829] } },
{ name: "Times Square", location: { type: "Point", coordinates: [-73.9851, 40.7580] } },
{ name: "Brooklyn Bridge", location: { type: "Point", coordinates: [-73.9969, 40.7061] } },
{ name: "Empire State Building", location: { type: "Point", coordinates: [-73.9857, 40.7488]
} },
{ name: "Statue of Liberty", location: { type: "Point", coordinates: [-74.0445, 40.6892] } }
])
// Create a geospatial index
geoDatabase> [Link]({ location: "2dsphere" })
Geospatial Queries:
1. $near (Find places near a certain point)
geoDatabase> [Link]({ location: { $near: { $geometry: { type: "Point",
coordinates: [-73.9851, 40.7580] }, $maxDistance: 5000 // distance in meters } }}).pretty()
2. $geoWithin (Find places within a specific area)
geoDatabase> [Link]({ location: { $geoWithin: { $geometry: { type: "Polygon",
coordinates: [ [ [-70.016, 35.715],
[-74.014, 40.717],
[-73.990, 40.730],
[-73.990, 40.715],
[-70.016, 35.715] ] ] } }}).pretty()
Bitwise Selectors:
test> use techDB
techDB> [Link]([
{ name: "Device A", status: 5 }, // Binary: 0101
{ name: "Device B", status: 3 }, // Binary: 0011
{ name: "Device C", status: 12 }, // Binary: 1100
{ name: "Device D", status: 10 }, // Binary: 1010
{ name: "Device E", status: 7 } // Binary: 0111
])
Bitwise Queries:
1. $bitsAllSet (Find documents where all bits are set)
techDB> [Link]({ status: { $bitsAllSet: [0, 2] }}).pretty()
2. $bitsAnySet (Find documents where any of the bits are set)
techDB> [Link]({ status: { $bitsAnySet: [1] }}).pretty()
3. $bitsAllClear (Find documents where all bits are clear)
techDB> [Link]({ status: { $bitsAllClear: [1, 3] }}).pretty()
4. $bitsAnyClear (Find documents where any of the bits are clear)
techDB> [Link]({ status: { $bitsAnyClear: [0] }}).pretty()
4. Create and demonstrate how projection operators ($, $elematch
and $slice) would be used in the MondoDB.
Creating Product:
test> use retailDB
switched to db retailDB
retailDB> [Link]([
{
name: "Laptop",
brand: "BrandA",
features: [
{ name: "Processor", value: "Intel i7" },
{ name: "RAM", value: "16GB" },
{ name: "Storage", value: "512GB SSD" }
],
reviews: [
{ user: "Alice", rating: 5, comment: "Excellent!" },
{ user: "Bob", rating: 4, comment: "Very good" },
{ user: "Charlie", rating: 3, comment: "Average" }
]
},
{
name: "Smartphone",
brand: "BrandB",
features: [
{ name: "Processor", value: "Snapdragon 888" },
{ name: "RAM", value: "8GB" },
{ name: "Storage", value: "256GB" }
],
reviews: [
{ user: "Dave", rating: 4, comment: "Good phone" },
{ user: "Eve", rating: 2, comment: "Not satisfied" }
]
}
])
1. The $ Projection Operator
Example: Find the product named “Laptop” and project the review from the user “Alice”.
retailDB> [Link](
{ name: "Laptop", "[Link]": "Alice" },
{ "reviews.$": 1 }
).pretty()
2. The $elemMatch Projection Operator
Example: Find the product named “Laptop” and project the review where the rating is
greater than 4.
retailDB> [Link](
{ name: "Laptop" },
{ reviews: { $elemMatch: { rating: { $gt: 4 } } } }
).pretty()
3. The $slice Projection Operator
Example: Find the product named “Smartphone” and project the first review.
retailDB> [Link](
{ name: "Smartphone" },
{ reviews: { $slice: 1 } }
).pretty()
5. Execute Aggregation operations ($avg, $min,$max, $push,
$addToSet etc.). students encourage to execute several queries to
demonstrate various aggregation operators)
Create the Sales Collection and Insert Documents
test> use salesDB
salesDB> [Link]([
{ date: new Date("2024-01-01"), product: "Laptop", price: 1200, quantity: 1, customer:
"Amar" },
{ date: new Date("2024-01-02"), product: "Laptop", price: 1200, quantity: 2, customer:
"Babu" },
{ date: new Date("2024-01-03"), product: "Mouse", price: 25, quantity: 5, customer:
"Chandra" },
{ date: new Date("2024-01-04"), product: "Keyboard", price: 45, quantity: 3, customer:
"Amar" },
{ date: new Date("2024-01-05"), product: "Monitor", price: 300, quantity: 1, customer:
"Babu" },
{ date: new Date("2024-01-06"), product: "Laptop", price: 1200, quantity: 1, customer:
"Deva" }
])
1. $avg (Average)
salesDB> [Link]([
{
$group: {
_id: "$product",
averagePrice: { $avg: "$price" }
}
} ]).pretty()
2. $min (Minimum)
salesDB> [Link]([
{
$group: {
_id: "$product",
minPrice: { $min: "$price" }
}
} ]).pretty()
3. $max (Maximum)
salesDB> [Link]([
{
$group: {
_id: "$product",
maxPrice: { $max: "$price" }
}
} ]).pretty()
4. $push (Push Values to an Array)
salesDB> [Link]([
{
$group: {
_id: "$customer",
products: { $push: "$product" }
}
} ]).pretty()
5. $addToSet (Add Unique Values to an Array)
salesDB> [Link]([
{
$group: {
_id: "$customer",
uniqueProducts: { $addToSet: "$product" }
}
} ]).pretty()
Experiment 6:
Execute Aggregation Pipeline and its operations (pipeline must
contain match,group, sort,project, $skip etc.)
// Switch to the restaurantDB database
use restaurantDB
// Insert sample documents into the restaurants collection
[Link]([
{
name: "Biryani House",
cuisine: "Indian",
location: "Jayanagar",
reviews: [
{ user: "Aarav", rating: 5, comment: "Amazing biryani!" },
{ user: "Bhavana", rating: 4, comment: "Great place!" }
] },
{
name: "Burger Joint",
cuisine: "American",
location: "Koramangala",
reviews: [
{ user: "Chirag", rating: 3, comment: "Average burger" },
{ user: "Devika", rating: 4, comment: "Good value" }
] },
{
name: "Pasta House",
cuisine: "Italian",
location: "Rajajinagar",
reviews: [
{ user: "Esha", rating: 5, comment: "Delicious pasta!" },
{ user: "Farhan", rating: 4, comment: "Nice ambiance" }
] },
{
name: "Curry Palace",
cuisine: "Indian",
location: "Jayanagar",
reviews: [
{ user: "Gaurav", rating: 4, comment: "Spicy and tasty!" },
{ user: "Harini", rating: 5, comment: "Best curry in town!" }
] },
{
name: "Taco Stand",
cuisine: "Mexican",
location: "Jayanagar",
reviews: [
{ user: "Ishaan", rating: 5, comment: "Fantastic tacos!" },
{ user: "Jaya", rating: 4, comment: "Very authentic" }
] }])
// Run the aggregation pipeline query to display reviews summary
[Link]([
{
$match: {
location: "Jayanagar"
}},
{
$unwind: "$reviews"
},
{
$group: {
_id: "$name",
averageRating: { $avg: "$[Link]" },
totalReviews: { $sum: 1 }
}},
{
$sort: {
averageRating: -1
} },
{
$project: {
_id: 0,
restaurant: "$_id",
averageRating: 1,
totalReviews: 1
} },
{
$skip: 1
} ]).pretty()
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.
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 descending order.
5. $project: Restructure the output to include only the restaurant name, average
rating, and total reviews.
6. $skip: Skip the first document.
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
test> use vacationRentals
switched to db vacationRentals
vacationRentals>
create the listingsAndReviews collection and insert sample documents. Here are a few
example documents to illustrate the structure:
vacationRentals> [Link]([
{
listing_url: "[Link]
name: "Beautiful Apartment",
address: {
street: "123 Main Street",
suburb: "Central",
city: "Metropolis",
country: "Wonderland"
},
host: {
name: "Alice",
picture_url: "[Link]
} },
{
listing_url: "[Link]
name: "Cozy Cottage",
address: {
street: "456 Another St",
suburb: "North",
city: "Smallville",
country: "Wonderland"
},
host: {
name: "Bob",
picture_url: ""
} },
{
listing_url: "[Link]
name: "Modern Condo",
address: {
street: "789 Side Road",
suburb: "East",
city: "Gotham",
country: "Wonderland"
},
host: {
name: "Charlie",
picture_url: "[Link]
}
} ])
Query to Find Listings with Host Picture URLs
[Link](
{
"host.picture_url": { $exists: true, $ne: "" }
},
{
listing_url: 1,
name: 1,
address: 1,
"host.picture_url": 1
} ).pretty()
b. Using E-commerce collection write a query to display reviews summary
// Switch to the ecommerce database
use ecommerce
// Insert sample documents into the products collection
[Link]([
{
product_id: 1,
name: "Laptop",
category: "Electronics",
price: 1200,
reviews: [
{ user: "Alice", rating: 5, comment: "Excellent!" },
{ user: "Bob", rating: 4, comment: "Very good" },
{ user: "Charlie", rating: 3, comment: "Average" }
]
},
{
product_id: 2,
name: "Smartphone",
category: "Electronics",
price: 800,
reviews: [
{ user: "Dave", rating: 4, comment: "Good phone" },
{ user: "Eve", rating: 2, comment: "Not satisfied" },
{ user: "Frank", rating: 5, comment: "Amazing!" }
]
},
{
product_id: 3,
name: "Headphones",
category: "Accessories",
price: 150,
reviews: [
{ user: "Grace", rating: 5, comment: "Great sound" },
{ user: "Heidi", rating: 3, comment: "Okay" }
]
}
])
// Run the aggregation query to display reviews summary
[Link]([
{
$unwind: "$reviews"
},
{
$group: {
_id: "$name",
totalReviews: { $sum: 1 },
averageRating: { $avg: "$[Link]" },
comments: { $push: "$[Link]" }
} },
{
$project: {
_id: 0,
product: "$_id",
totalReviews: 1,
averageRating: 1,
comments: 1
}
} ]).pretty()
// Switch to MoviesDB (will create the database if it doesn't exist)
use MoviesDB
// Create the Movies collection
[Link]("Movies")
// Insert sample documents into the Movies collection
[Link]([
{ title: "Inception", director: "Christopher Nolan", genre: "Science Fiction", year: 2010,
ratings: { imdb: 8.8, rottenTomatoes: 87 } },
{ title: "The Matrix", director: "Wachowskis", genre: "Science Fiction", year: 1999, ratings: {
imdb: 8.7, rottenTomatoes: 87 } },
{ title: "The Godfather", director: "Francis Ford Coppola", genre: "Crime", year: 1972,
ratings: { imdb: 9.2, rottenTomatoes: 97 } },
{ title: "Pulp Fiction", director: "Quentin Tarantino", genre: "Crime", year: 1994, ratings: {
imdb: 8.9, rottenTomatoes: 92 } },
{ title: "The Shawshank Redemption", director: "Frank Darabont", genre: "Drama", year:
1994, ratings: { imdb: 9.3, rottenTomatoes: 91 } },
{ title: "The Dark Knight", director: "Christopher Nolan", genre: "Action", year: 2008,
ratings: { imdb: 9.0, rottenTomatoes: 94 } },
{ title: "Fight Club", director: "David Fincher", genre: "Drama", year: 1999, ratings: { imdb:
8.8, rottenTomatoes: 79 } }
])
// =====================
// 1. Creating Indexes
// =====================
// a. Unique Index: Prevent duplicate movie titles
[Link]({ title: 1 }, { unique: true })
// b. Sparse Index: Index only documents that include the "awards" field
// Update a document to include an "awards" field (only for demonstration)
[Link](
{ title: "The Godfather" },
{ $set: { awards: "Best Picture" } }
// Create the sparse index on the awards field
[Link]({ awards: 1 }, { sparse: true })
// c. Compound Index: Optimize queries filtering by director and year
[Link]({ director: 1, year: -1 })
// d. Multikey Index: Create an index on an array field "actors"
// Update a document to include an actors array
[Link](
{ title: "Inception" },
{ $set: { actors: ["Leonardo DiCaprio", "Joseph Gordon-Levitt", "Elliot Page"] } }
// Create the index on the actors field (automatically becomes a multikey index)
[Link]({ actors: 1 })
// =====================
// 2. Query Optimization
// =====================
// Run a query with an explain plan to see if the indexes are used
// This query searches for movies directed by "Christopher Nolan"
[Link]({ director: "Christopher Nolan" }).explain("executionStats")
// Switch to a new or existing database
use CatalogDB
// Create a new collection
[Link]("CatalogData")
// Insert sample documents
[Link]([
{ title: "[Link] Guide", description: "Learn server-side programming with [Link] and
JavaScript." },
{ title: "MongoDB Basics", description: "This book introduces MongoDB and NoSQL
database design." },
{ title: "Advanced Python", description: "Master advanced concepts in Python for data
science and web development." },
{ title: "Java Programming", description: "Comprehensive guide to Java programming for
beginners." },
{ title: "Python Data Analysis", description: "Data analysis and visualization with Python and
Pandas." },
{ title: "Web Development", description: "Covers HTML, CSS, JavaScript, and modern
frameworks." }
])
// Create a text index on title and description fields
[Link]({ title: "text", description: "text" })
// =========================================
// a. Demonstrate Text Search for a Given Word
// =========================================
// Find documents that match the word "Python"
[Link]({ $text: { $search: "Python" } })
// ==============================================
// b. Exclude Documents with Certain Words/Phrases
// ==============================================
// 1. Exclude documents containing the word "Java"
[Link]({ $text: { $search: "-Java" } })
// 2. Exclude documents containing the phrase "data science"
[Link]({ $text: { $search: "-\"data science\"" } })
// 3. Include "Python" but exclude "Pandas"
[Link]({ $text: { $search: "Python -Pandas" } })
// Optional: View the index created
[Link]()
// Step 1: Use the appropriate database
use CatalogDB
// Step 2: Insert sample data (if not already inserted)
[Link]([
{ title: "[Link] Guide", description: "Learn server-side programming with [Link] and
JavaScript." },
{ title: "MongoDB Basics", description: "This book introduces MongoDB and NoSQL
database design." },
{ title: "Advanced Python", description: "Master advanced concepts in Python for data
science and web development." },
{ title: "Java Programming", description: "Comprehensive guide to Java programming for
beginners." },
{ title: "Python Data Analysis", description: "Data analysis and visualization with Python and
Pandas." },
{ title: "Web Development", description: "Covers HTML, CSS, JavaScript, and modern
frameworks." }
])
// Step 3: Create a text index on relevant fields
[Link]({ title: "text", description: "text" })
// Step 4: Aggregation pipeline for text search
[Link]([
$match: {
$text: {
$search: "Python" // keyword to search
}
},
$project: {
title: 1,
description: 1,
score: { $meta: "textScore" } // include relevance score
},
$sort: {
score: -1 // sort by relevance
])