Program9_WM
Program9_WM
9. 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.
"category": "Electronics"
}
{
"category": "Electronics"
}
{
"category": "Audio"
"category": "Computers"
}
In MongoShell
>use CatalogDB
To enable text search, you need to create a text index on the fields you want to search. Here, we'll
create a text index on the name and description fields:
Output:
Now, let's perform a text search. Suppose you want to search for products related to the word "latest":
Output:
db.products.find({ $text: { $search: "High performance" } })
Output:
b. Develop queries to illustrate excluding documents with certain words and phrases.
In MongoDB, you can use the $not operator combined with the $regex operator to exclude
documents that contain certain words or phrases. Below are some examples of queries to
illustrate this.
"_id": 1,
"_id": 2,
}
{
"_id": 3,
}
{
"_id": 4,
"title": "Introduction to Databases",
"content": "This article gives an introduction to databases in general."
}
To exclude documents that contain the word "advanced" in the ‘content’ field:
db.articles.find({
"content": {
$not: /advanced/
})
Output:
To exclude documents that contain either "improve" or "performance" in the ‘content’ field:
db.articles.find({
"content": {
$not: /(improve|performance)/
}
})
Output:
To exclude documents that contain the phrase "MongoDB Basics" in the ‘title’ field:
db.articles.find({
"title": {
})
Output:
To exclude documents that contain "MongoDB" in the ‘title’ or "advanced" in the ‘content’:
db.articles.find({
$and: [
})
Output: