การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ
ผู้เรียนจะค้นหาด้วย $text โดยใช้วลีในเครื่องหมายคำพูด คำที่ปฏิเสธ และนิพจน์หลายคำ พร้อมตรวจสอบวิธีที่ MongoDB จับคู่เอกสาร
การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
The $text Query Operator
Once a text index exists, you run keyword searches with the $text operator inside a find() filter. The value is an object with a $search string containing the words or phrases you are looking for. MongoDB tokenises your search string the same way it tokenised the indexed fields, then returns documents where at least one indexed field contains a matching token.
// Simple keyword search
db.articles.find({ $text: { $search: 'mongodb index' } });
// This returns documents that contain 'mongodb' OR 'index'
// (or their stemmed variants) in any indexed fieldMulti-Word Searches: OR Semantics
By default, a $text search with multiple words uses OR semantics: a document matches if it contains any of the words. So 'mongodb index' returns documents containing 'mongodb' or 'index' or both. The relevance score (textScore) is higher for documents that contain more of the search terms, but all matching documents are returned regardless.
// OR semantics: matches docs with 'mongodb' OR 'index'
db.articles.find(
{ $text: { $search: 'mongodb index' } },
{ score: { $meta: 'textScore' }, title: 1 }
).sort({ score: { $meta: 'textScore' } });
// Documents with BOTH words score higher and appear firstPhrase Searches With Double Quotes
To require an exact phrase, wrap it in escaped double quotes inside the $search string. A phrase search requires the words to appear together and in that order. Documents that only contain some of the phrase words but not the exact sequence will not match. Phrase searches are more precise but can miss relevant documents with slightly different wording.
// Phrase search: 'database index' must appear as a phrase
db.articles.find({
$text: { $search: '"database index"' }
});
// Only matches documents where 'database' and 'index'
// appear together as a phrase, not just anywhere in the text
// Combined phrase and keyword:
db.articles.find({
$text: { $search: '"database index" mongodb' }
});Negation With the Minus Sign
Prefix a word with a minus sign (-) to exclude documents that contain that word. You cannot use negation alone—you must pair it with at least one positive search term. Negation is useful when a keyword is too broad and you want to filter out a specific unwanted meaning, like 'java -coffee' to find programming articles about Java, not the beverage.
// Exclude results containing 'relational'
db.articles.find({
$text: { $search: 'database -relational' }
});
// Find NoSQL content but exclude SQL mentions
db.articles.find({
$text: { $search: 'nosql document store -sql -table' }
});Combining Phrases and Negation
You can freely mix phrases, keywords, and negation in a single $search string. MongoDB processes each term independently: quoted groups are phrase searches, minus-prefixed words are exclusions, and remaining bare words are optional keyword matches. This composability lets you express moderately complex search logic without a dedicated search engine.
// Find articles about 'index tuning' that mention 'mongodb'
// but exclude anything about 'elasticsearch'
db.articles.find({
$text: {
$search: '"index tuning" mongodb -elasticsearch'
}
});Case Insensitivity
$text searches are case-insensitive by default. MongoDB lowercases all tokens during indexing and during the search, so 'MongoDB', 'MONGODB', and 'mongodb' all match the same indexed tokens. You do not need to normalise search input before running a $text query.
// All three queries return the same results
db.articles.find({ $text: { $search: 'MongoDB' } });
db.articles.find({ $text: { $search: 'MONGODB' } });
db.articles.find({ $text: { $search: 'mongodb' } });The $language Option
By default, $text uses the language configured on the text index. You can override this per query with the $language option. This is useful for multilingual content collections where documents stored in different languages should be searched with the appropriate stop word list and stemming algorithm.
// Override language for a specific search
db.articles.find({
$text: {
$search: 'base de datos',
$language: 'spanish'
}
});
// Or disable stop words and stemming entirely
db.articles.find({
$text: {
$search: 'databases',
$language: 'none' // exact token match, no stemming
}
});The $caseSensitive Option
While case-insensitive search is the default, you can enable case-sensitive text search with $caseSensitive: true. This is rarely needed but useful when your content has case-significant identifiers like class names or command names. Note: case-sensitive text search is significantly slower because it cannot use the pre-lowercased index entries.
// Case-sensitive search (slower)
db.docs.find({
$text: {
$search: 'MongoDB',
$caseSensitive: true // 'mongodb' would NOT match
}
});
// Case-insensitive (default, fast)
db.docs.find({
$text: { $search: 'mongodb' } // matches MongoDB, MONGODB, mongodb
});The $diacriticSensitive Option
By default, MongoDB text search is diacritic-insensitive: 'café' and 'cafe' are treated as the same word. You can enable $diacriticSensitive: true to distinguish accented characters. This matters for languages like French, German, or Spanish where diacritics change meaning. Like case sensitivity, diacritic-sensitive search is slower because it bypasses pre-normalised index entries.
// Diacritic-insensitive (default)
db.articles.find({ $text: { $search: 'cafe' } });
// Matches: 'cafe', 'café', 'cáfe'
// Diacritic-sensitive
db.articles.find({
$text: {
$search: 'cafe',
$diacriticSensitive: true
}
});
// Only matches: 'cafe' (not 'café')Text Search in Aggregation Pipelines
You can use $text in aggregation pipelines by placing a $match stage with the text filter as the very first stage. This lets MongoDB push the text search to the index before applying subsequent pipeline stages. You can then project the textScore, group results by category, or limit the number of matches—all server-side.
db.articles.aggregate([
// MUST be the first stage to use the text index
{ $match: { $text: { $search: 'mongodb aggregation' } } },
{ $addFields: { score: { $meta: 'textScore' } } },
{ $sort: { score: -1 } },
{ $limit: 10 },
{ $project: { title: 1, score: 1, category: 1 } }
]);Counting Text Search Results
To count how many documents match a text query, use countDocuments() with the $text filter or add a $count stage at the end of an aggregation pipeline. Avoid using count() (deprecated) and be aware that estimatedDocumentCount() cannot take a filter—always use countDocuments() for filtered counts.
// Count matching documents
const total = await db.articles.countDocuments({
$text: { $search: 'mongodb tutorial' }
});
console.log('Matches:', total);
// In an aggregation pipeline
db.articles.aggregate([
{ $match: { $text: { $search: 'mongodb tutorial' } } },
{ $count: 'total' }
]);Quick Check
Test your understanding of $text query options from this lesson.
Lesson Recap
In this lesson you learned: bare words use OR semantics and match any of the search terms, double-quoted phrases require an exact word sequence, and minus-prefixed words exclude documents containing that term. Next up we sort results by text relevance score using $meta.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ”
ผู้เรียนจะค้นหาด้วย $text โดยใช้วลีในเครื่องหมายคำพูด คำที่ปฏิเสธ และนิพจน์หลายคำ พร้อมตรวจสอบวิธีที่ MongoDB จับคู่เอกสาร คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างดัชนีข้อความบนฟิลด์สตริง
- การเรียกใช้การค้นหา $text ด้วยวลีและการปฏิเสธ
- การเรียงลำดับตามคะแนนข้อความด้วย $meta
- ข้อจำกัดของดัชนีข้อความและเวลาที่ควรใช้ Atlas Search