การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด
ผู้เรียนจะค้นหาด้วยตัวดำเนินการข้อความ วลี และไวลด์การ์ดภายในขั้นตอนการรวมข้อมูล $search และเลือกแสดงคะแนนการค้นหา
การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
The $search Aggregation Stage
Atlas Search queries are written using the $search aggregation stage—a special pipeline stage that routes the query to the Lucene engine rather than the MongoDB query planner. The $search stage must be the first stage in an aggregation pipeline. Inside it, you specify an operator (like text, phrase, or wildcard) that determines how the query string is matched against indexed documents.
The text Operator: Keyword Search
The text operator is the standard keyword search operator. It tokenizes the query string using the same analyzer used to build the index, then looks for documents containing those tokens. It supports multi-word queries where any word can match (OR semantics by default) and the path field specifies which indexed fields to search in—either a specific field name or all fields via { wildcard: '*' }.
db.articles.aggregate([
{
$search: {
index: 'default',
text: {
query: 'mongodb aggregation pipeline',
path: 'content' // search in the 'content' field only
}
}
},
{
$project: {
title: 1,
author: 1,
score: { $meta: 'searchScore' }
}
},
{ $limit: 10 }
])Searching Multiple Fields
The path field in a text operator can be a single field name, an array of field names, or the wildcard { wildcard: '*' } to search all indexed fields. When searching multiple fields, MongoDB combines results using the best score across fields. Searching fewer, more relevant fields typically produces better precision than searching all fields.
db.products.aggregate([
{
$search: {
text: {
query: 'noise cancelling headphones',
path: ['name', 'description', 'tags'] // search in these three fields
}
}
},
{ $limit: 20 }
])
// Or search all indexed fields:
db.products.aggregate([
{
$search: {
text: {
query: 'wireless bluetooth',
path: { wildcard: '*' }
}
}
}
])The phrase Operator: Exact Phrase Matching
The phrase operator requires the query terms to appear in order and adjacent to each other in the document (like quoting a phrase in a search engine). This is more restrictive than text but much more precise—searching for 'machine learning' as a phrase will not match documents that only contain 'learning' and 'machine' in different sentences. Use slop to allow some words between terms.
db.articles.aggregate([
{
$search: {
phrase: {
query: 'machine learning model',
path: 'content' // all three words must appear in order
}
}
},
{ $project: { title: 1, score: { $meta: 'searchScore' } } }
])
// With slop: allows up to 1 word between the terms
db.articles.aggregate([
{
$search: {
phrase: {
query: 'neural network',
path: 'content',
slop: 1 // allows 'neural deep network' to match
}
}
}
])The wildcard Operator: Pattern Matching
The wildcard operator matches documents where the field value matches a glob-style pattern using * (matches any sequence of characters) and ? (matches any single character). It searches against the indexed token values, so the behavior depends on the analyzer. For keyword-analyzed fields, it matches the entire stored string. Set allowAnalyzedField: true to use wildcard on analyzed fields (use with care—expensive for leading wildcards).
// Match SKUs starting with 'PROD-'
db.products.aggregate([
{
$search: {
wildcard: {
query: 'PROD-*',
path: 'sku', // keyword-analyzed field
allowAnalyzedField: false
}
}
}
])
// Match domains ending in '.org'
db.users.aggregate([
{
$search: {
wildcard: {
query: '*.org',
path: 'email',
allowAnalyzedField: true
}
}
}
])Projecting the Search Score
Atlas Search computes a relevance score for each result document indicating how well it matches the query. Access this score in a $project stage using { $meta: 'searchScore' }. By default, $search returns results in descending score order (most relevant first). Projecting the score also lets you filter on it—for example, discarding low-relevance results below a threshold.
db.articles.aggregate([
{
$search: {
text: { query: 'cloud computing', path: 'body' }
}
},
{
$project: {
title: 1,
author: 1,
publishedAt: 1,
relevanceScore: { $meta: 'searchScore' } // include the score
}
},
// Only show results with score above 0.5
{ $match: { relevanceScore: { $gt: 0.5 } } },
{ $limit: 10 }
])Combining $search With $match for Post-Filtering
You can follow $search with a $match stage to apply additional structured filters—for example, text search for 'headphones' and then filter to products with price under $100. However, use $searchMeta or the filter clause inside $search for pre-filtering on indexed fields, as post-match $match runs after all results are fetched and may be slower than filtering within the search stage.
db.products.aggregate([
{
$search: {
compound: {
must: [
{ text: { query: 'wireless headphones', path: 'name' } }
],
filter: [
// Pre-filter inside $search: much more efficient
{ range: { path: 'price', lte: 100 } },
{ equals: { path: 'inStock', value: true } }
]
}
}
},
{ $project: { name: 1, price: 1, score: { $meta: 'searchScore' } } }
])The range Operator for Numeric and Date Filtering
The range operator allows numeric or date range filtering inside the $search stage. This is more efficient than a post-search $match because Lucene applies the filter before fetching documents. Use gte, gt, lte, and lt bounds. The range operator works on fields indexed with type 'number' or 'date' in the Atlas Search index mapping.
db.jobs.aggregate([
{
$search: {
compound: {
must: [
{ text: { query: 'backend developer', path: 'title' } }
],
filter: [
{
range: {
path: 'postedAt',
gte: new Date('2024-01-01'),
lte: new Date('2024-12-31')
}
},
{
range: {
path: 'salaryMin',
gte: 80000
}
}
]
}
}
}
])The equals Operator for Exact Field Matching
The equals operator performs an exact equality match on a field—similar to MongoDB's standard equality filter but executed inside the Lucene engine. It works on boolean, number, date, objectId, and string fields. Using equals inside $search (rather than a post-search $match) allows Lucene to combine it with the text query efficiently using its bitset and skip-list optimizations.
db.listings.aggregate([
{
$search: {
compound: {
must: [
{ text: { query: 'beachfront villa', path: 'description' } }
],
filter: [
{ equals: { path: 'available', value: true } },
{ equals: { path: 'bedrooms', value: 3 } }
]
}
}
}
])Performance: $search vs Native Text Index
Atlas Search generally outperforms MongoDB's native text indexes for complex queries because Lucene's inverted index is more sophisticated. However, for simple keyword lookups on small collections, the native $text operator may be sufficient. Key advantages of Atlas Search: better relevance scoring, per-field boosting, fuzzy matching, autocomplete, facets, and no one-text-index-per-collection limitation. Choose Atlas Search when you need any of these features.
Index Name Specification
When you have multiple Atlas Search indexes on a collection, specify the index field inside $search to select which index to use. If you omit it, Atlas Search uses the index named 'default'. Using named indexes allows different query types to use different index configurations—for example, a 'standard' index for keyword search and an 'autocomplete' index for type-ahead suggestions.
// Use the 'products_fulltext' search index
db.products.aggregate([
{
$search: {
index: 'products_fulltext', // named index
text: {
query: 'standing desk ergonomic',
path: ['title', 'description']
}
}
}
]);
// Falls back to 'default' if index is not specified:
db.products.aggregate([
{
$search: {
text: { query: 'monitor 4K', path: 'title' }
}
}
]);Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: $search must be the first pipeline stage and takes an operator like text, phrase, or wildcard, the text operator matches any token from the query while phrase requires tokens to appear in order, and use the compound operator with filter clauses to combine text search with structured filters efficiently inside the Lucene engine. Next up we explore autocomplete and fuzzy matching for typo-tolerant search.
คำถามที่พบบ่อย
บทเรียน “การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด”
ผู้เรียนจะค้นหาด้วยตัวดำเนินการข้อความ วลี และไวลด์การ์ดภายในขั้นตอนการรวมข้อมูล $search และเลือกแสดงคะแนนการค้นหา คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างดัชนีการค้นหา Atlas
- การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด
- การเติมข้อความอัตโนมัติและการจับคู่แบบคลุมเครือ
- แฟกเก็ตและการค้นหาแบบผสม