MongoDB Academy · บทเรียน

แฟกเก็ตและการค้นหาแบบผสม

ผู้เรียนจะรวมเงื่อนไขการค้นหาหลายข้อด้วยตัวดำเนินการแบบผสม และคำนวณจำนวนแบบแฟกเก็ตสำหรับตัวกรองหมวดหมู่ควบคู่กับผลลัพธ์การค้นหา

บทเรียน 4 จาก 413 ขั้นตอน

แฟกเก็ตและการค้นหาแบบผสม เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Are Search Facets?

Facets are aggregated counts of how many search results fall into each category of a field. You have seen facets on e-commerce sites: 'Brand: Nike (142), Adidas (89), Puma (45)' or 'Price: Under $50 (230), $50-$100 (185)'. In Atlas Search, facets are computed server-side alongside the search results in a single query using the $searchMeta stage or the facet collector within $search.

Configuring Fields for Faceting

To facet on a field, it must be indexed with the stringFacet (for string categories) or numberFacet/dateFacet (for range buckets) data type in the Atlas Search index mapping. You can add a facet type alongside a string type on the same field. Standard string-typed fields are not facetable—you must explicitly add the facet type to your index definition.

// Index mapping with facetable fields
{
  'mappings': {
    'dynamic': false,
    'fields': {
      'title': { 'type': 'string', 'analyzer': 'lucene.standard' },
      'category': [
        { 'type': 'string' },         // for filtering
        { 'type': 'stringFacet' }     // for facet counts
      ],
      'brand': { 'type': 'stringFacet' },
      'price': [
        { 'type': 'number' },
        { 'type': 'numberFacet' }
      ]
    }
  }
}

The $searchMeta Stage for Facet Counts

Use $searchMeta (instead of $search) when you need only the metadata (facet counts, total results) without returning the actual documents. This is efficient for re-computing facet counts when a filter changes. The stage returns a single document containing the facet buckets. Combine it with a separate $search query to get both documents and facets in two parallel requests.

// Get facet counts for categories and brands
db.products.aggregate([
  {
    $searchMeta: {
      index: 'default',
      facet: {
        operator: {
          text: { query: 'wireless headphones', path: 'title' }
        },
        facets: {
          categoriesFacet: {
            type: 'string',
            path: 'category',
            numBuckets: 10  // return up to 10 category buckets
          },
          brandsFacet: {
            type: 'string',
            path: 'brand',
            numBuckets: 20
          }
        }
      }
    }
  }
])

Number Range Facets

For numeric fields, define explicit price range buckets using the numericFacet type with a boundaries array and a default bucket name for values that fall outside all boundaries. The boundaries define bin edges—[0, 50, 100, 500] creates buckets 0–50, 50–100, and 100–500. Each bucket in the result shows the count of matching documents in that range.

db.products.aggregate([
  {
    $searchMeta: {
      facet: {
        operator: { text: { query: 'running shoes', path: 'name' } },
        facets: {
          priceRanges: {
            type: 'number',
            path: 'price',
            boundaries: [0, 50, 100, 200, 500],
            // Produces: '$0-$50', '$50-$100', '$100-$200', '$200-$500'
            default: 'Other'  // for products outside all ranges
          }
        }
      }
    }
  }
])

The compound Operator: Combining Search Clauses

The compound operator is the most powerful Atlas Search operator—it lets you combine multiple search clauses using four clause types: must (all must match, contributes to score), mustNot (must not match), should (optional, but boosts score if they match), and filter (must match but does not affect score). This mirrors Elasticsearch's bool query and enables sophisticated relevance ranking.

db.jobs.aggregate([
  {
    $search: {
      compound: {
        must: [
          // Required: title must contain 'senior engineer'
          { text: { query: 'senior engineer', path: 'title' } }
        ],
        should: [
          // Optional boost: prefer remote jobs
          { equals: { path: 'remote', value: true } },
          // Optional boost: prefer jobs with high salary
          { range: { path: 'salary', gte: 150000 } }
        ],
        filter: [
          // Must match but does NOT affect score
          { equals: { path: 'active', value: true } }
        ],
        mustNot: [
          // Exclude contract roles
          { equals: { path: 'type', value: 'contract' } }
        ]
      }
    }
  }
])

minimumShouldMatch: Controlling OR Logic

By default, should clauses are entirely optional—a document that matches none of them still appears in results if must clauses match. Set minimumShouldMatch to require that at least N should clauses match. This converts the behavior from pure OR to a 'match at least N' semantic, letting you express queries like 'must have title match AND at least one of: location, skills, or salary match'.

db.candidates.aggregate([
  {
    $search: {
      compound: {
        must: [
          { text: { query: 'python developer', path: 'title' } }
        ],
        should: [
          { text: { query: 'machine learning', path: 'skills' } },
          { text: { query: 'tensorflow pytorch', path: 'skills' } },
          { range: { path: 'experienceYears', gte: 3 } }
        ],
        minimumShouldMatch: 1  // must match at least 1 should clause
      }
    }
  }
])

Score Boosting in compound Queries

You can control relevance score contributions from each clause using the score option. Boosting multiplies the base score from that clause by a factor—useful when a match in the title is more important than a match in the description. constant scoring replaces the calculated score with a fixed value, useful for filter-like clauses you want to affect ranking but not dominate it.

db.articles.aggregate([
  {
    $search: {
      compound: {
        should: [
          {
            text: {
              query: 'mongodb performance',
              path: 'title',
              score: { boost: { value: 3.0 } }  // title matches worth 3x more
            }
          },
          {
            text: {
              query: 'mongodb performance',
              path: 'body',
              score: { boost: { value: 1.0 } }  // body matches at normal weight
            }
          }
        ]
      }
    }
  }
])

Getting Documents and Facets Together

A common pattern in search UIs is to return both the result documents and the facet counts in parallel. The most efficient approach uses the Atlas Search facet collector: pair $searchMeta for facet metadata with a separate $search query for documents, running both in parallel from your application. Alternatively, use $search with a $facet aggregation stage after it (this performs two passes but is simpler).

// Run both queries in parallel
const searchQuery = 'wireless headphones';
const [documents, facets] = await Promise.all([
  // Query 1: get matching documents
  db.collection('products').aggregate([
    { $search: { text: { query: searchQuery, path: 'name' } } },
    { $project: { name: 1, price: 1, category: 1, score: { $meta: 'searchScore' } } },
    { $limit: 20 }
  ]).toArray(),

  // Query 2: get facet counts for the same query
  db.collection('products').aggregate([
    { $searchMeta: { facet: { operator: { text: { query: searchQuery, path: 'name' } },
      facets: { cats: { type: 'string', path: 'category', numBuckets: 10 } } } } }
  ]).toArray()
]);

console.log('Results:', documents.length, 'Facets:', facets[0].facet.cats.buckets);

Applying Active Facet Filters

When a user clicks a facet to filter results (e.g., 'Category: Electronics'), you need to add that selection as a filter clause in the compound operator. This narrows both the result documents and the remaining facet counts to only matching items. It is important to apply facet filters in the filter (not must) clause so they do not affect relevance scoring.

async function searchWithFacetFilter(query, selectedCategory) {
  const filterClauses = [];
  if (selectedCategory) {
    filterClauses.push({ equals: { path: 'category', value: selectedCategory } });
  }

  return db.collection('products').aggregate([
    {
      $search: {
        compound: {
          must: [{ text: { query, path: 'name' } }],
          filter: filterClauses  // apply active facet selections
        }
      }
    },
    { $project: { name: 1, price: 1, category: 1 } },
    { $limit: 20 }
  ]).toArray();
}

Facet Result Structure

The result of a $searchMeta with facets is a single document containing a facet key. Each facet you defined is a sub-key containing a buckets array. Each bucket has an _id (the facet value) and a count. For number facets, each bucket also has a lowerBound and upperBound. Parse this structure in your application to render the facet filter sidebar.

// $searchMeta result structure:
// [
//   {
//     'facet': {
//       'categoriesFacet': {
//         'buckets': [
//           { '_id': 'Electronics', 'count': 142 },
//           { '_id': 'Audio', 'count': 89 },
//           { '_id': 'Accessories', 'count': 45 }
//         ]
//       },
//       'priceRanges': {
//         'buckets': [
//           { '_id': '0.0', 'count': 23 },  // 0 to 50
//           { '_id': '50.0', 'count': 67 },  // 50 to 100
//           { '_id': '100.0', 'count': 101 } // 100 to 200
//         ]
//       }
//     }
//   }
// ]

Date Facets for Time-Based Navigation

Date facets work similarly to number facets—you define explicit bucket boundaries as Date objects. This enables time-based navigation like 'Published this week (12)', 'Published this month (47)', 'Published this year (183)'. Define the boundaries as an array of dates and Atlas Search counts documents whose date field falls within each range. Date facets are useful for filtering blog posts, job listings, events, and any time-sensitive content.

db.articles.aggregate([
  {
    $searchMeta: {
      facet: {
        operator: { text: { query: 'mongodb', path: 'title' } },
        facets: {
          publishedDate: {
            type: 'date',
            path: 'publishedAt',
            boundaries: [
              new Date('2024-01-01'),
              new Date('2024-04-01'),
              new Date('2024-07-01'),
              new Date('2024-10-01'),
              new Date('2025-01-01')
            ],
            default: 'Other'
          }
        }
      }
    }
  }
])

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: facets require stringFacet/numberFacet types in the index mapping and are computed with $searchMeta, the compound operator combines must, mustNot, should, and filter clauses for sophisticated relevance queries, and filter clauses narrow results without affecting the relevance score, while must clauses do both. Next up we explore connecting to MongoDB with the official Node.js driver.

เริ่มต้นได้ฟรี

เรียนรู้ JavaScript ด้วย AI tutor — ฟรี

เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป

คอร์ส
30
บทเรียน
120

คำถามที่พบบ่อย

บทเรียน “แฟกเก็ตและการค้นหาแบบผสม” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “แฟกเก็ตและการค้นหาแบบผสม” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “แฟกเก็ตและการค้นหาแบบผสม”

ผู้เรียนจะรวมเงื่อนไขการค้นหาหลายข้อด้วยตัวดำเนินการแบบผสม และคำนวณจำนวนแบบแฟกเก็ตสำหรับตัวกรองหมวดหมู่ควบคู่กับผลลัพธ์การค้นหา คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 4 จากทั้งหมด 4 บทเรียน

บทเรียน “แฟกเก็ตและการค้นหาแบบผสม” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การสร้างดัชนีการค้นหา Atlas
  2. การเขียนการค้นหา $search: ข้อความ วลี และไวลด์การ์ด
  3. การเติมข้อความอัตโนมัติและการจับคู่แบบคลุมเครือ
  4. แฟกเก็ตและการค้นหาแบบผสม
← กลับไปที่ MongoDB Academy