การสร้างดัชนีข้อความบนฟิลด์สตริง
ผู้เรียนจะสร้างดัชนีข้อความแบบฟิลด์เดียวและแบบไวลด์การ์ด และทำความเข้าใจการแยกคำเป็นโทเค็นและการลดรูปคำที่ MongoDB ใช้
การสร้างดัชนีข้อความบนฟิลด์สตริง เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
What Is a Text Index?
A text index is a special MongoDB index type that tokenises and stems the words in string fields so you can run full-text keyword searches. Unlike a regular index that stores exact field values, a text index breaks each string into individual words, removes stop words (like 'the', 'is'), and stores the resulting tokens in a B-tree. This makes it possible to search for 'mongodb tutorial' and match documents containing 'mongodb tutorials'.
Creating a Single-Field Text Index
Pass the string 'text' as the index direction to tell MongoDB to create a text index on that field. You can only have one text index per collection, but it can span multiple fields. The index builds in the background and maintains the token store automatically as documents are inserted or updated.
// Text index on the 'description' field
db.products.createIndex({ description: 'text' });
// Now you can run full-text searches
db.products.find({ $text: { $search: 'wireless headphones' } });Multi-Field Text Indexes
A single text index can cover multiple string fields, allowing $text queries to search across all of them simultaneously. Each field can be assigned a different weight to influence relevance scoring—a match in a high-weight field like title counts more than a match in a lower-weight field like body.
// Multi-field text index with weights
db.articles.createIndex(
{ title: 'text', body: 'text', tags: 'text' },
{
weights: {
title: 10, // matches in title score 10x
tags: 5,
body: 1
},
name: 'idx_articles_text'
}
);Wildcard Text Indexes
If you want to search across every string field in a document without listing them all, you can use a wildcard text index with the special '$**' key. MongoDB will automatically tokenise all string-valued fields at any nesting level. This is convenient but creates a larger index than a targeted multi-field text index, so use it thoughtfully.
// Index ALL string fields in every document
db.articles.createIndex({ '$**': 'text' });
// This now searches title, body, author, tags, comments.text, etc.
db.articles.find({ $text: { $search: 'nosql' } });Tokenisation and Stemming
When MongoDB indexes a string like 'Learning MongoDB databases', it tokenises it into individual words (learning, mongodb, databases), removes stop words, and then stems each token to its root form (e.g., databases → databas). Stemming means a search for 'database' matches documents containing 'databases', 'database', or 'databasing' without needing wildcards.
// The text 'Learning MongoDB databases' is indexed as:
// tokens (after stop-word removal and stemming):
// 'learn', 'mongodb', 'databas'
// All of these queries match the document:
db.articles.find({ $text: { $search: 'learning' } });
db.articles.find({ $text: { $search: 'database' } });
db.articles.find({ $text: { $search: 'databases' } });Stop Words Are Ignored
Stop words are common words like 'the', 'is', 'at', 'which', and 'on' that carry little meaning and are excluded from the text index to keep it lean. If your search term consists entirely of stop words, the $text query returns no results. Stop word lists are language-specific and controlled by the default_language option on the index.
// Create text index with explicit language
db.articles.createIndex(
{ body: 'text' },
{ default_language: 'english' } // english stop words (default)
);
// Stop words for English include: the, is, are, at, on, in, a, an...
// Searching for 'the' alone returns nothing
db.articles.find({ $text: { $search: 'the' } }); // 0 resultsLanguage Support
MongoDB's text index supports many languages including english, french, german, spanish, portuguese, italian, dutch, and more. Each language has its own stop word list and stemming rules. You can also set the language to 'none' to disable stop word removal and stemming, treating every token as a literal string.
// Spanish text index
db.articulos.createIndex(
{ contenido: 'text' },
{ default_language: 'spanish' }
);
// Per-document language override (store language in a field)
db.posts.createIndex(
{ body: 'text' },
{ language_override: 'lang' } // read language from doc.lang field
);
db.posts.insertOne({ body: 'Bonjour le monde', lang: 'french' });One Text Index Per Collection Rule
MongoDB enforces a hard limit of one text index per collection. This means you must plan all the string fields you want searchable and include them in a single multi-field text index definition. Trying to create a second text index on the same collection will throw an error. If you need to add a field to an existing text index, you must drop and recreate the index.
// First text index on 'title'
db.articles.createIndex({ title: 'text' });
// Trying to add a second text index FAILS:
// db.articles.createIndex({ body: 'text' });
// Error: only one text index per collection allowed
// Correct approach: drop old, recreate with both fields
db.articles.dropIndex('title_text');
db.articles.createIndex({ title: 'text', body: 'text' });Text Index Storage Overhead
Text indexes can be significantly larger than regular indexes because they store one entry per unique token per document rather than one entry per document. A document with a 500-word description might add hundreds of index entries. Monitor text index size with db.collection.stats().indexSizes and consider whether a dedicated search service (Atlas Search, Elasticsearch) would be more efficient for very large corpora.
// Check text index size
const stats = db.articles.stats();
console.log('Index sizes:', stats.indexSizes);
// idx_articles_text might be 10x larger than a regular index
// on the same number of documentsCombining Text Index With Other Indexes
A text index can be combined with a regular field in a compound index. For example, you can index { category: 1, description: 'text' } to allow filtering by category alongside the text search. In this case the category equality filter dramatically reduces the number of token entries the planner has to examine, making the text query much faster.
// Compound text index with category prefix
db.products.createIndex({ category: 1, description: 'text' });
// This query can use the compound text index efficiently:
// MongoDB filters by category first, then does text search
db.products.find({
category: 'electronics',
$text: { $search: 'wireless' }
});Verifying the Text Index
After creating a text index, use db.collection.getIndexes() to confirm it was created with the correct fields and weights, and run a simple $text query with .explain() to verify the query planner uses a TEXT stage. A TEXT stage in the plan means the text index is actively being used for keyword matching.
// Inspect the text index definition
db.articles.getIndexes().filter(idx => idx.textIndexVersion !== undefined);
// Verify TEXT stage in explain output
db.articles
.find({ $text: { $search: 'mongodb' } })
.explain();
// Look for: { stage: 'TEXT', ... }Quick Check
Test your understanding of MongoDB text indexes from this lesson.
Lesson Recap
In this lesson you learned: text indexes tokenise and stem string fields to enable full-text keyword searches, only one text index is allowed per collection but it can span multiple fields with custom weights, and language determines stop words and stemming rules. Next up we learn to run $text queries with phrases and negation.
คำถามที่พบบ่อย
บทเรียน “การสร้างดัชนีข้อความบนฟิลด์สตริง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างดัชนีข้อความบนฟิลด์สตริง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างดัชนีข้อความบนฟิลด์สตริง”
ผู้เรียนจะสร้างดัชนีข้อความแบบฟิลด์เดียวและแบบไวลด์การ์ด และทำความเข้าใจการแยกคำเป็นโทเค็นและการลดรูปคำที่ MongoDB ใช้ คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างดัชนีข้อความบนฟิลด์สตริง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างดัชนีข้อความบนฟิลด์สตริง
- การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ
- การเรียงลำดับตามคะแนนข้อความด้วย $meta
- ข้อจำกัดของดัชนีข้อความและเวลาที่ควรใช้ Atlas Search