Sorting by Text Score With $meta
Learners will project and sort by textScore to surface the most relevant documents at the top of results.
What Is textScore?
When a $text query runs, MongoDB computes a relevance score for every matching document called the textScore. This score reflects how well the document matches the search terms: more occurrences of the search terms, matches in higher-weighted fields, and matches of rarer tokens all increase the score. By default, results are not sorted by score; you must request the sort explicitly.
Projecting textScore With $meta
To include the relevance score in your results, add a projection field using { $meta: 'textScore' }. You can name this field anything you like (conventionally score). The $meta expression reads metadata computed during query execution—textScore is the only metadata value currently supported in this context.
db.articles.find(
{ $text: { $search: 'mongodb performance' } },
{
title: 1,
score: { $meta: 'textScore' } // project the relevance score
}
);