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:
- Create a text index: Before you can use the
$textoperator 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 thedb.collection.createIndex()method with thetextindex type:
db.collection.createIndex({ field1: 'text', field2: 'text' })This will create a text index on the field1 and field2 fields of the collection.
- Use the
$textoperator in an aggregation pipeline: Once you have a text index, you can use the$textoperator 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.
- Sort the results by relevance score: To sort the search results by relevance score, you can use the
$metaoperator with thetextScorevalue in a$sortstage:
{ $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.
- Optional: Limit the number of results: You can use the
$limitoperator 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.