On this page本页内容
In the aggregation pipeline, text search is available via the use of the $text
query operator in the $match
stage.
For general $text
operator restrictions, see operator restrictions.
In addition, text search in the aggregation pipeline has the following restrictions:
$match
stage that includes a $text
must be the first stage in the pipeline.text
operator can only occur once in the stage.text
operator expression cannot appear in $or
or $not
expressions.$meta
aggregation expression in the $sort
stage.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
for details on accessing the score for projection or sort.
The metadata is only available after the $match
stage that includes the $text
operation.
The following examples assume a collection articles
that has a text index on the field subject
:
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.
To sort by the text search score, include a {$meta:
"textScore"}
expression in the $sort
stage. The following example matches on either the term cake
or tea
, sorts by the textScore
in descending order, and returns only the title
field in the results set.
The specified metadata determines the sort order. For example, the "textScore"
metadata sorts in descending order. See $meta
for more information on metadata as well as an example of overriding the default sort order of the metadata.
The "textScore"
metadata is available for projections, sorts, and conditions subsequent the $match
stage that includes the $text
operation.
The following example matches on either the term cake
or tea
, projects the title
and the score
fields, and then returns only those documents with a score
greater than 1.0
.