• If the compound text index includes keys preceding the text index key, to perform a $text search, the query predicate must include equality match conditions on the preceding keys. 

## See also: 

Text Indexes (page 500) 

## Text Search in the Aggregation Pipeline 

New in version 2.6. In the aggregation pipeline, text search is available via the use of the $text query operator in the $match stage. 

## Restrictions 

Text search in the aggregation pipeline has the following restrictions: 

• The $match stage that includes a $text must be the first stage in the pipeline. 

• A text operator can only occur once in the stage. 

• The text operator expression cannot appear in $or or $not expressions. 

• The text search, by default, does not return the matching documents in order of matching scores. Use the $meta aggregation expression in the $sort stage. 

## Text Score 

The $text operator assigns a score to each document that contains the search term in the indexed fields. The score represents the relevance of a document to a given text search query. The score can be part of a $sort pipeline specification as well as part of the projection expression. The { $meta: "textScore" } expression provides information on the processing of the $text operation. See $meta aggregation for details on accessing the score for projection or sort. 

The metadata is only available after the $match stage that includes the $text operation. 

Examples The following examples assume a collection articles that has a text index on the field subject : 

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

## Calculate the Total Views for Articles that Contains a Word 

The following aggregation searches for the term cake in the $match stage and calculates the total views for the matching documents in the $group stage. 

db.articles.aggregate( [ { $match: { $text: { $search: "cake" } } }, { $group: { _id: null , views: { $sum: "$views" } } } ] ) 

