0Pricing
MongoDB Academy · 강의

$meta로 텍스트 점수에 따라 정렬하기

학습자는 textScore로 프로젝션하고 정렬해 가장 관련성 높은 문서가 결과 상단에 표시되도록 합니다.

$meta로 텍스트 점수에 따라 정렬하기은(는) CoddyKit의 무료 MongoDB Academy 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 MongoDB Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

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
  }
);

Sorting by textScore

To sort results by relevance, pass { score: { $meta: 'textScore' } } to .sort(). MongoDB sorts in descending order by default for textScore (highest relevance first). You must project the score field in the same query when sorting by it—if you omit the projection, MongoDB will still sort correctly but won't return the score value to the client.

db.articles
  .find(
    { $text: { $search: 'mongodb performance index' } },
    { title: 1, score: { $meta: 'textScore' } }
  )
  .sort({ score: { $meta: 'textScore' } });
// Results ordered: most relevant first

How textScore Is Calculated

MongoDB's textScore is based on a variant of TF-IDF (Term Frequency – Inverse Document Frequency) logic. Term frequency: a document with the search word appearing 10 times scores higher than one where it appears once. Field weights: matches in a field with weight 10 score 10× higher than matches in a weight-1 field. Index density: rarer words that appear in fewer documents contribute more to the score than very common words.

// Index with weights: title matches count more
db.articles.createIndex(
  { title: 'text', body: 'text' },
  { weights: { title: 10, body: 1 } }
);

// A document where 'mongodb' appears in the title
// scores 10x higher than one where it only appears in the body

$meta in Aggregation Pipelines

In aggregation pipelines, use { $meta: 'textScore' } inside a $addFields or $project stage to attach the score, then pipe into $sort. Remember: the $match stage with $text must come first in the pipeline so MongoDB can compute the score before other stages transform the document stream.

db.articles.aggregate([
  { $match: { $text: { $search: 'nosql tutorial' } } },
  { $addFields: { score: { $meta: 'textScore' } } },
  { $sort: { score: -1 } },
  { $limit: 5 },
  { $project: { _id: 0, title: 1, score: 1 } }
]);

Combining textScore Sort With Other Sorts

You can combine textScore sorting with other sort keys. For example, sort by relevance first, then by date as a tiebreaker. MongoDB processes sort keys left to right, so put textScore first to prioritise relevance. The additional sort keys only determine order among documents with equal textScore values.

db.articles
  .find(
    { $text: { $search: 'mongodb' } },
    { title: 1, createdAt: 1, score: { $meta: 'textScore' } }
  )
  .sort({
    score: { $meta: 'textScore' },  // relevance first
    createdAt: -1                    // then newest
  });

Filtering by Minimum Score

If you want to return only highly relevant documents, you can filter by a minimum textScore using the $meta expression inside a $match stage (in aggregation) after the text match. This is not possible with a direct find() filter; you need the aggregation pipeline to compute the score first and then filter on it.

db.articles.aggregate([
  { $match: { $text: { $search: 'mongodb nosql' } } },
  { $addFields: { score: { $meta: 'textScore' } } },
  { $match: { score: { $gte: 1.5 } } },  // only high-relevance docs
  { $sort: { score: -1 } },
  { $project: { title: 1, score: 1 } }
]);

textScore Does Not Guarantee Absolute Values

The textScore values are relative within a query result set, not absolute or comparable across different queries or different collection states. A score of 2.5 today might become 3.1 tomorrow if you add more documents to the collection (changing term frequency calculations). Use textScore for sorting within a result set, not as a stored quality metric.

// Scores vary depending on collection content
// Useful for RANKING within a search result, not for thresholds
// Bad pattern:
const MIN_SCORE = 2.0;  // this threshold will drift as data grows

// Better pattern:
// Return the top N results sorted by score
db.articles
  .find({ $text: { $search: 'mongodb' } }, { score: { $meta: 'textScore' } })
  .sort({ score: { $meta: 'textScore' } })
  .limit(10);

Pagination of Text Search Results

Standard skip()/limit() pagination works with text search, but it has the usual performance issue at deep offsets. Since results are relevance-ranked rather than ordered by a stable field, keyset pagination is not straightforward for text results. A common pattern is to use offset pagination for the first few pages (where most users stop) and consider Atlas Search for deeper, more consistent pagination at scale.

// Page 1 (skip 0)
db.articles
  .find({ $text: { $search: 'mongodb' } }, { score: { $meta: 'textScore' } })
  .sort({ score: { $meta: 'textScore' } })
  .skip(0).limit(10);

// Page 2 (skip 10) - gets slower on large result sets
db.articles
  .find({ $text: { $search: 'mongodb' } }, { score: { $meta: 'textScore' } })
  .sort({ score: { $meta: 'textScore' } })
  .skip(10).limit(10);

textScore in Mongoose

When using Mongoose, you access textScore via the { meta: 'textScore' } option on a schema path or by using .select() with the score meta projection. Mongoose wraps the MongoDB driver's API, so the underlying concept is the same—you just need to know the Mongoose syntax for projecting and sorting by metadata.

// Mongoose text search with score projection
const results = await Article.find(
  { $text: { $search: 'mongodb nosql' } },
  { score: { $meta: 'textScore' } }  // same $meta syntax
).sort({ score: { $meta: 'textScore' } });

console.log(results.map(r => ({ title: r.title, score: r.score })));

When textScore Is Not Enough

Native text indexes work well for simple use cases, but they lack features like autocomplete, faceted search, synonyms, and custom ranking functions. When you need these capabilities, MongoDB Atlas Search (built on Apache Lucene) provides a much richer relevance scoring engine with BM25 scoring, boosting, and explain output for tuning relevance.

// Atlas Search provides richer scoring with the score option
// db.articles.aggregate([
//   { $search: {
//       text: { query: 'mongodb', path: 'title', score: { boost: { value: 3 } } },
//   } },
//   { $addFields: { score: { $meta: 'searchScore' } } },
//   { $sort: { score: -1 } }
// ]);
// --> Use Atlas Search when textScore is insufficient

Quick Check

Test your understanding of sorting by text score with $meta.

Lesson Recap

In this lesson you learned: textScore is a per-document relevance score computed during $text queries, { $meta: 'textScore' } projects and sorts by this score, and field weights and term frequency determine the score magnitude. Next up we cover text index limitations and when Atlas Search is the better choice.

자주 묻는 질문

“$meta로 텍스트 점수에 따라 정렬하기” 강의는 무료인가요?

네 — “$meta로 텍스트 점수에 따라 정렬하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 MongoDB Academy 강의 전체를 잠금 해제할 수 있습니다. MongoDB Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“$meta로 텍스트 점수에 따라 정렬하기”에서 뭘 배우나요?

학습자는 textScore로 프로젝션하고 정렬해 가장 관련성 높은 문서가 결과 상단에 표시되도록 합니다. 브라우저에서 직접 실행하는 실습 코드로 MongoDB Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

MongoDB Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 MongoDB Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“$meta로 텍스트 점수에 따라 정렬하기” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 MongoDB Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 MongoDB Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 문자열 필드에 텍스트 인덱스 만들기
  2. 구문과 부정을 사용해 $text 쿼리 실행하기
  3. $meta로 텍스트 점수에 따라 정렬하기
  4. 텍스트 인덱스의 한계와 Atlas Search를 사용할 시점
← MongoDB Academy(으)로 돌아가기