Sling Academy
Home/MongoDB/MongoDB: Performing text search using $text operator (with examples)

MongoDB: Performing text search using $text operator (with examples)

Last updated: February 03, 2024

Introduction

MongoDB is a popular NoSQL database that provides high performance, high availability, and easy scalability. One of the powerful features of MongoDB is its text search capability, which allows developers to perform content-based queries on their data. In this tutorial, we will explore how to use the $text operator to perform text searches in MongoDB. We will begin with basic examples and gradually move towards more advanced usage, so let’s dive in.

Before we begin, make sure you have MongoDB installed on your system and have basic knowledge of MongoDB operations. To perform text searches, you also need a collection with at least one text index.

Creating a Text Index

The first step to utilizing text search is to create a text index on the field that you want to search. Here’s how you create a text index:

db.collection.createIndex({fieldname: 'text'})

For example, if you want to search through blog posts titles:

db.blogposts.createIndex({title: 'text'})

Now you have a text index on the title field.

After creating a text index, you can start performing text searches using the $text operator and $search keyword. Here is the syntax for a basic text search:

db.collection.find({$text: {$search: 'search term'}})

Searching for blog posts containing ‘MongoDB’:

db.blogposts.find({$text: {$search: 'MongoDB'}})

The query will return all blog posts with the term ‘MongoDB’ in their title.

Using Text Search Options

MongoDB text search allows you to use several options to refine your search. Here are some of the most common ones:

  • Case Sensitivity: By default, text searches are case-insensitive. However, they can be made case-sensitive using the $caseSensitive option set to true.
  • Diactric Sensitivity: MongoDB’s text search is diacritic-sensitive, but it can be adjusted using the $diacriticSensitive option.

Searching with Case Sensitivity

To perform a case-sensitive search, you’ll use this syntax:

db.collection.find({
  $text: {
    $search: 'search term',
    $caseSensitive: true
  }
})

Searching with Diacritic Sensitivity

To perform a diacritic-sensitive search, use this syntax:

db.collection.find({
  $text: {
    $search: 'search term',
    $diacriticSensitive: true
  }
})

Searching for a Phrase

If you want to search for an exact phrase in MongoDB, you’ll utilize quotation marks within the search term:

db.collection.find($text: {$search: '"exact phrase"'})

Excluding Words

Sometimes you may want to exclude documents that contain certain words from your search results. You can do this by prefixing the word with a minus (-) sign:

db.collection.find({$text: {$search: 'MongoDB -SQL'}})

This query will return documents that contain ‘MongoDB’ but not ‘SQL’.

Text Search with Sorting and Projecting

Beyond searching, you may also want to sort by text search relevance or project certain fields. Here’s how you would sort results by relevance:

db.collection.find(
  {$text: {$search: 'MongoDB'}},
  {score: {$meta: 'textScore'}}
).sort({score: {$meta: 'textScore'}})

To project only the title field and text search score:

db.collection.find(
  {$text: {$search: 'MongoDB'}},
  {_id: 0, title: 1, score: {$meta: 'textScore'}}
)

Conclusion

In this tutorial, we have covered how to perform text searches in MongoDB using the $text operator. We looked at creating a text index, basic search techniques, and more advance query options like case and diacritic sensitivity, excluding terms, and sorting and projecting using text search relevance. Mastering text search in MongoDB can significantly improve the user experience by allowing users to easily find relevant data within your application.

Next Article: MongoDB: Using $expr to query using aggregation expressions

Previous Article: MongoDB: Using $where Operator to Query Using JavaScript Expression

Series: MongoDB Tutorials

MongoDB

You May Also Like

  • MongoDB: How to combine data from 2 collections into one
  • Hashed Indexes in MongoDB: A Practical Guide
  • Partitioning and Sharding in MongoDB: A Practical Guide (with Examples)
  • Geospatial Indexes in MongoDB: How to Speed Up Geospatial Queries
  • Understanding Partial Indexes in MongoDB
  • Exploring Sparse Indexes in MongoDB (with Examples)
  • Using Wildcard Indexes in MongoDB: An In-Depth Guide
  • Matching binary values in MongoDB: A practical guide (with examples)
  • Understanding $slice operator in MongoDB (with examples)
  • Caching in MongoDB: A practical guide (with examples)
  • CannotReuseObject Error: Attempted illegal reuse of a Mongo object in the same process space
  • How to perform cascade deletion in MongoDB (with examples)
  • MongoDB: Using $not and $nor operators to negate a query
  • MongoDB: Find SUM/MIN/MAX/AVG of each group in a collection
  • References (Manual Linking) in MongoDB: A Developer’s Guide (with Examples)
  • MongoDB: How to see all fields in a collection (with examples)
  • Type checking in MongoDB: A practical guide (with examples)
  • How to query an array of subdocuments in MongoDB (with examples)
  • MongoDB: How to compare 2 documents (with examples)