Open In App

Using $search and Compound Operators in MongoDB

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB is a NoSQL database that stores the data in a document format called BSON (similar to JSON) Unlike traditional relational databases MongoDB doesn’t depend on tables and rows. It uses collections and documents making it suitable for modern and highly interactive applications.

The $search operator and compound operators in MongoDB are useful for querying and manipulating data. The $search operator helps to easily search text data whereas compound operators help to combine criteria for data searching.

What is the $search Operator?

The $search operator enables text search within MongoDB collections. It allows users to perform full-text search queries on text fields allowing them to find documents that match a given text query.

Suppose we have a collection named articles which comprises multiple documents representing various articles. Each document contains fields such as title, author, description and content. The document structure within the articles collection is as follows:

Query:

{
"_id": ObjectId("61f94f20b4d48e8d278bcfd3"),
"title": "Introduction to MongoDB",
"content": "MongoDB is a popular NoSQL database...",
"category": "Technology"
}

In this example, suppose we want to search for specific text within the content field, regardless of its position in the text. We can achieve this by using the $search operator in a MongoDB query.

Implementing Text Search in MongoDB Using $search Operator

Step 1: Creating a Text Index

Before using the $search operator, it is necessary to create a text index on the field that we want to search. So let’s create an index on the content field.

Query:

db.articles.createIndex({ content: "text" })

Output:

creating_index_in_mongo

Creating a Text Index

Explanation: This command creates a text index on the content field within the articles collection and fast efficient text searches.

Step 2: Performing a Text Search

With the text index in place, we can now execute a text search using the $search operator. The syntax for searching text with the $search operator is as follows.

Query:

db.articles.find({ $text: { $search: "MongoDB" } })

Output:

using_search_operator_in_mongodb

Performing a Text Search

Explanation: This query searches for documents in the articles collection where the content field contains the term “MongoDB“. The $search operator ensures that the search is conducted efficiently and returning relevant documents regardless of the text’s position within the field.

What is a Compound Operator in MongoDB?

Compound operators allow the users to create more complex queries by combining multiple conditions using logical operators such as $and, $or, and $nor. These operators help to define between conditions and allowing for greater flexibility in querying MongoDB data.

Suppose we have a collection named users containing documents representing users. Each document has fields like name, age and gender. Here are some example documents.

Query:

[{
"_id": ObjectId("61f94f20b4d48e8d278bcfd3"),
"name": "Rahul",
"age": 30,
"gender": "female"
},
{
"_id": ObjectId("61f94f20b4d48e8d278bcfd4"),
"name": "Gaurav",
"age": 45,
"gender": "male"
},
{
"_id": ObjectId("61f94f20b4d48e8d278bcfd5"),
"name": "Vijay",
"age": 20,
"gender": "male"
}]

Explanation: Now, let’s learn how different compound operators are used to query the data from the above document.

1. Using the $and Operator

The $and operator combines multiple conditions, and all conditions must be true for a document to be returned.

Query:

db.users.find({ $and: [{ age: { $gte: 25 } }, { age: { $lte: 40 } }] })

Output:

and_operator_in_mongodb

Using $and Operator

Explanation: The above query is used to find documents in the users collection where the age field is greater than or equal to 25 and less than or equal to 40. The $and operator is used to combine multiple expressions into a single query, ensuring that all conditions must be met for a document to be included in the result.

2. Using the $or Operator

The $or operator combines multiple conditions, and at least one condition must be true for a document to be returned.

Query:

db.users.find({ $or: [{ age: { $lt: 18 } }, { age: { $gt: 65 } }] })

Output:

or_operator_in_mongodb

Using $or Operator

Explanation: The above query is used to find documents in the users collection where the age field is less than 18 or greater than 65. The $or operator is used to combine multiple expressions into a single query and allowing documents to be included in the result if any of the conditions are met.

3. Using the $nor Operator

The $nor operator combines multiple conditions, and none of the conditions must be true for a document to be returned.

Query:

db.users.find({ $nor: [{ age: { $lt: 18 } }, { age: { $gt: 65 } }] })

Output:

nor_operaton_in_mongodb

Using $nor Operator

Explanation: The above query is used to find documents in the users collection where the age field is neither less than 18 nor greater than 65. The $nor operator is used to negate a list of one or more query expressions and allowing documents to be included in the result if none of the conditions are met.

Using $search Operator with Compound Operators

Combining the $search operator with compound operators in MongoDB provides even more powerful querying capabilities. Suppose we have a scenario where we want to find articles from the articles collection that contain the term “MongoDB” in the content field and belong to the “Technology” category.

Query:

db.articles.find({
$and: [
{ $text: { $search: "MongoDB" } },
{ category: "Technology" }
]
})

Output:

$searchOperatorwithCompoundOperators

Using $search Operator with Compound Operators

Explanation: Here the $text operator searches for the term MongoDB within the content field and $and operator combines the text search condition with another condition.The second condition {category: “Technology” } ensures that only articles from the “Technology” category are retrieved.

Conclusion

Overall, the MongoDB $search operator enables efficient full-text searches within collections while compound operators like $and, $or and $nor allow users to combine multiple criteria for fast querying. These tools empower users to extract insights swiftly and flexibly from MongoDB data. Mastering these features enhances MongoDB’s utility for modern applications.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads