Skip to content

$text operator

Learn how to use MongoDB's $text operator to perform text searches with relevance scoring in aggregation pipelines for ranking search results.

The $text operator in MongoDB is used to perform a text search on one or more fields of a collection. When used in an aggregation pipeline, it can generate a relevance score for each document that matches the search query, which can be useful for sorting or ranking search results.

Here's how the $text operator works in more detail:

  1. Create a text index: Before you can use the $text operator to search for text, you need to create a text index on one or more fields of the collection. You can create a text index using the db.collection.createIndex() method with the text index type:
db.collection.createIndex({ field1: 'text', field2: 'text' })

This will create a text index on the field1 and field2 fields of the collection.

  1. Use the $text operator in an aggregation pipeline: Once you have a text index, you can use the $text operator in an aggregation pipeline to search for text. Here's an example:
db.collection.aggregate([
  { $match: { $text: { $search: 'search query' } } },
  { $sort: { score: { $meta: 'textScore' } } }
])

In this example, we're using the $text operator inside a $match stage to search for the text "search query" across all fields in the collection that have a text index. MongoDB will return all documents that contain the search query, and it will also generate a score for each document that indicates how relevant it is to the search query.

  1. Sort the results by relevance score: To sort the search results by relevance score, you can use the $meta operator with the textScore value in a $sort stage:
{ $sort: { score: { $meta: 'textScore' } } }

This will sort the search results in descending order based on the relevance score, so that the most relevant documents appear first.

  1. Optional: Limit the number of results: You can use the $limit operator in a final stage to limit the number of search results returned by the aggregation pipeline:
{ $limit: 10 }

This will limit the search results to the first 10 documents returned by the pipeline.

That's a brief overview of how the $text operator works in MongoDB. It's a powerful tool for performing text searches on large datasets and can be used to generate relevance scores for search results, which can be used for ranking or sorting purposes.

Tags

MongoDBText SearchAggregation PipelineDatabase IndexingQuery Operators