การเรียงลำดับตามคะแนนข้อความด้วย $meta
ผู้เรียนจะเลือกแสดงและเรียงลำดับตาม textScore เพื่อให้เอกสารที่เกี่ยวข้องที่สุดปรากฏด้านบนของผลลัพธ์
การเรียงลำดับตามคะแนนข้อความด้วย $meta เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 firstHow 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 insufficientQuick 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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การเรียงลำดับตามคะแนนข้อความด้วย $meta”
ผู้เรียนจะเลือกแสดงและเรียงลำดับตาม textScore เพื่อให้เอกสารที่เกี่ยวข้องที่สุดปรากฏด้านบนของผลลัพธ์ คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การเรียงลำดับตามคะแนนข้อความด้วย $meta” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างดัชนีข้อความบนฟิลด์สตริง
- การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ
- การเรียงลำดับตามคะแนนข้อความด้วย $meta
- ข้อจำกัดของดัชนีข้อความและเวลาที่ควรใช้ Atlas Search