Installation

Install as Agent Plugin Recommended
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install mongodb-search-and-ai@skills-hub

Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled). Plugin mongodb-search-and-ai v1.0.0 follows the Agent Plugins spec.

Install with the gh extension
gh skills-hub install mongodb-search-and-ai

Don't have the extension? Run gh extension install samueltauil/skills-hub first.

Download and extract to your repository:

.github/skills/mongodb-search-and-ai/

Extract the ZIP to .github/skills/ in your repo. The folder name must match mongodb-search-and-ai for Copilot to auto-discover it.

Skill Files (8)

SKILL.md 8.8 KB
---
name: mongodb-search-and-ai
description: |
  Covers everything about search in MongoDB: Atlas Search (full-text), Vector Search (semantic), and Hybrid Search. Use this skill for ANY question about MongoDB search, including open-ended and explanatory ones asked before the user has any data or use case — 'how does search work in MongoDB?', 'I'm new to MongoDB search, where do I start?', 'what's the difference between Atlas Search and Vector Search?', 'which search type should I use?', 'what is vector search?', 'how does automated embedding work?', 'can you explain hybrid search?'. Do not answer these from general knowledge; use this skill. Also use to build search features: full-text queries, autocomplete, fuzzy matching, faceted search, semantic similarity, embeddings, RAG, text containment or substring matching ('contains', 'includes'), case-insensitive or multi-field text search, and filtering across many fields. Provides workflows for choosing a search type, creating indexes, writing queries, and optimizing performance via the MongoDB MCP server.
license: Apache-2.0
metadata:
  version: "1.1.0"
  labelText: "Add, optimize, or troubleshoot Atlas search or vector search. Understand the optimal approach to search and build effective indexes and queries."
---

# MongoDB Search and AI Recommendations Skill

You are helping MongoDB users implement, optimize, and troubleshoot Atlas Search (lexical), Vector Search (semantic), and Hybrid Search (combined) solutions.

## Core Principles

1. **Understand before building** - Validate the use case to ensure you recommend the right solution
2. **Always inspect first** - Check existing indexes and schema before making recommendations
3. **Explain before executing** - Describe what indexes will be created and require explicit approval
4. **Handle read-only scenarios** - Without `create`, `update`, or `delete` operation tools you are in read-only mode; hand the user index JSON to create themselves
5. **Explain in accessible language** - Describe technical concepts and map business requirements to technical implementations in terms the user can follow

## Workflow

### 0. Check for a Quickstart Request

`references/quick-start.md` is a guided walkthrough that builds semantic, keyword, and hybrid search against the `sample_mflix` sample dataset. It is a teaching tour, not a way to build search for the user's own data.

**Do not read `references/quick-start.md` until the user has chosen the tour.** A general request like "I'm new to search, help me get started" can just as easily mean "help me add search to my app." Use AskUserQuestion:

> "Two ways I can take this — which fits better?"

- **Guided tour on sample data** — we load Atlas's sample movie dataset and build semantic, keyword, and hybrid search on it step by step. Best for learning how each type works.
- **Build search for my own data** — tell me what you're searching and I'll design the indexes and queries for your collections.

Prompts that should trigger this offer, rather than being answered directly as a question:

- "I'm new to MongoDB, how does search work?", "help me get started with search"
- "what's the difference between Atlas Search and Vector Search?", "which search type should I use?"
- "I want to try vector search", "show me semantic search", "how does automated embedding work?"
- "I want to try keyword search", "show me full-text search", "I want to try hybrid search"

Skip the offer only when the intent is already unambiguous:

- **Explicit tour request** ("give me a guided tour", "walk me through search using sample data") — load `references/quick-start.md` and start at its Step 0.
- **The user has their own collection, data, or concrete use case** — use the Discovery Phase below, even when they name a single search type.

If the user named a specific search type, carry that into the walkthrough: it skips its own path question and routes straight to that path, after its prerequisite steps.

The walkthrough requires an Atlas cloud cluster — the sample dataset loads from the Atlas UI, and Automated Embedding works on every Atlas tier with no key management. Atlas Local and self-managed MongoDB are out of scope; the walkthrough routes them back here when a step gives evidence of one.

Otherwise, continue with the Discovery Phase.

### 1. Discovery Phase

**Check the environment:**
- Use `list-databases` and `list-collections` to understand available data
- If the user mentions a collection, use `collection-schema` to inspect field structure
- Use `collection-indexes` to see existing indexes
- Use `atlas-inspect-cluster` to determine the cluster's MongoDB version

**Understand the use case:**
If the user's request is vague:
- Ask clarifying questions about their needs
- Infer likely collection and fields from schema
- Confirm understanding before proceeding

Common questions to ask:
- What are users searching for? (products, movies, documents, etc.)
- What fields contain the searchable content?
- Are they searching by free text, or by similarity to an existing item (e.g. "given movie A, find similar movies")?
- Do they need exact matching, fuzzy matching, or semantic similarity?
- Do they need filters (price ranges, categories, dates)?
- Do they need autocomplete/typeahead functionality?
- Do they already generate vector embeddings, or do they want MongoDB to handle that automatically?

### 2. Determine Search Type and Consult the Reference File

Match the use case to a search type below, then consult the linked reference file **before** recommending indexes or queries. Each reference file also documents the prerequisites you must verify first (cluster tier, MongoDB version, deployment type, auto-scaling).

**Atlas Search (Lexical/Full-Text):**
Use when users need:
- Keyword matching with relevance scoring
- Fuzzy matching for typo tolerance
- Autocomplete/typeahead
- Faceted search with filters
- Language-specific text analysis
- Token-based search
- Lexical search with views

→ Consult both `references/lexical-search-indexing.md` (index) and `references/lexical-search-querying.md` (query).

**Automated Embedding (Semantic search, no embedding code):**
Use when users need:
- Semantic / vector search without writing embedding code
- No existing vector pipeline or embedding infrastructure
- Quick setup: MongoDB auto-generates and manages embeddings using Voyage AI models
- Text data already stored in Atlas that they want to search by meaning
- RAG or AI agent memory with minimal setup

→ Consult `references/automated-embedding.md`.

**Vector Search (Semantic, bring your own embeddings):**
Use when users need:
- Semantic similarity with their own pre-generated embeddings
- A specific embedding model not provided by Voyage AI
- Image, audio, or multimodal embeddings (Automated Embedding is text-only)
- Self-managed MongoDB without Voyage AI API key configured
- Vector search with views

→ Consult `references/vector-search.md`.

**Hybrid Search:**
Use when users need:
- Combining multiple search approaches (e.g., vector + lexical, multiple text searches)
- Queries like "find action movies similar to 'epic space battles'" (combining keyword filtering with semantic similarity)
- Results that factor in multiple relevance criteria
- Uses `$rankFusion` (rank-based) or `$scoreFusion` (score-based) to merge pipelines

→ Consult `references/hybrid-search.md`, plus the lexical/vector files for the individual pipeline stages.

### 3. Execution and Validation

**Creating indexes:**
1. Explain the index configuration in plain language
2. Show the JSON structure
3. Ask what the user wants to name the index
4. Get explicit approval: "Should I create this index?"
5. Use MCP's `create-index` tool after approval
6. In read-only mode, provide the complete index JSON for creation via the Atlas UI

**Running queries:**
1. Show the aggregation pipeline
2. Execute using MCP's `aggregate` tool
3. Present results clearly

**Refining existing queries:**
1. Ask the user to share their current query
2. Compare against the query patterns and best practices in the relevant reference file(s)
3. Propose specific improvements with before/after examples
4. Run the revised query with `aggregate` to validate the results

## Anti-Patterns to Avoid

**NEVER recommend `$regex` or `$text` for search use cases.** Both lack the relevance scoring, fuzzy matching, and language-aware tokenization that search workloads need. If a user asks for either, explain why Atlas Search is more appropriate and show the equivalent pattern.

## Handling Edge Cases

- **Fields you can't find** — inspect available fields with `collection-schema`, then confirm the intended field with the user
- **A required field doesn't exist** — explain what to add and how (e.g., an embedding field for vector search)
- **Query fails or index missing** — verify with `collection-indexes`; if absent, the index must be created first
- **Multiple collections are relevant** — ask which one they mean, unless context makes it obvious
references/
automated-embedding.md 15.7 KB
# Automated Embedding

**Scope**: This guide covers configuring MongoDB Vector Search to automatically generate and manage vector embeddings — no embedding code or model infrastructure required (queries still run through a `$vectorSearch` aggregation pipeline). It documents the `autoEmbed` index type and text-query `$vectorSearch` syntax. For manual vector search (bring your own embeddings), see `vector-search.md`. For combining with lexical search, see `hybrid-search.md`.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Model Selection](#model-selection)
- [Index Definition](#index-definition)
- [Query Construction](#query-construction)
- [Item-to-Item Similarity](#item-to-item-similarity)
- [How It Works Internally](#how-it-works-internally)
- [Billing and Free Tokens](#billing-and-free-tokens)
- [Rate Limits](#rate-limits)
- [Management and Monitoring](#management-and-monitoring)
- [Troubleshooting](#troubleshooting)

## Prerequisites

Verify these prerequisites before creating an `autoEmbed` index or query. Tier and auto-scaling prerequisites can change across Atlas releases — confirm the current requirements in the official docs before acting.

### Atlas Clusters

Automated Embedding is supported on **all Atlas cluster tiers**: M0 (free), Flex, and M10+ dedicated.

**M10+ dedicated clusters require storage auto-scaling to be enabled.** If the user is on M10+ without storage auto-scaling, explain how to enable it in Atlas and wait for confirmation before proceeding to index creation.

### Self-Managed Deployments

Requires:
1. MongoDB 8.3+ with `mongot`
2. A Voyage AI API key for indexing
3. A Voyage AI API key for querying (recommended to use separate keys)
4. Keys configured in `mongot` during deployment

If the user is on a self-managed deployment without Voyage AI configured, offer an alternative: "You can still do semantic search by generating embeddings yourself and storing them in your documents — this works on any deployment. Want to go that route instead?" If yes, proceed with manual Vector Search using `vector-search.md`.

## Model Selection

All models use Voyage AI, hosted and managed by MongoDB (multi-tenant, US region, Google Cloud). Context window is **32,000 tokens** for all models. Text exceeding this is truncated at index time; queries exceeding it return a `context-limit-exceeded` error. (Pricing and rate limits can change—confirm current values in Atlas or official MongoDB documentation.)

| Model | Best For | Per 1K Tokens | Per 1M Tokens |
|---|---|---|---|
| `voyage-4-lite` | High-volume, cost-sensitive applications | $0.00002 | $0.02 |
| `voyage-4` | **(Recommended)** General text search, balanced performance | $0.00006 | $0.06 |
| `voyage-4-large` | Maximum accuracy, complex semantic relationships | $0.00012 | $0.12 |
| `voyage-code-4` | **(Recommended for code)** Code search, technical documentation | $0.00012 | $0.12 |
| `voyage-code-3` | Legacy code model — use `voyage-code-4` instead | $0.00018 | $0.18 |

**Decision guide:**
- Default / unknown use case → `voyage-4`
- Large collection, cost is a concern → `voyage-4-lite`
- High-stakes retrieval where accuracy matters most → `voyage-4-large`
- Codebase or technical docs search → `voyage-code-4`

**`voyage-code-4` requires an Atlas deployment.** On self-managed deployments, use `voyage-code-3` for code and technical documentation.

**Free tokens:** 200 million tokens per model, one-time, shared across the entire Atlas organization. Does not refresh. See [Billing and Free Tokens](#billing-and-free-tokens) below for how consumption and invoicing work.

## Index Definition

### Syntax

```javascript
{
  "fields": [
    {
      "type": "autoEmbed",
      "modality": "text",
      "path": "<text-field-to-embed>",
      "model": "<embedding-model>"
    },
    {
      "type": "filter",    // Optional: index one or more fields as filters to enable pre-filtering / scoped search
      "path": "<field-to-filter-on>"
    }
  ]
}
```

### Fields

The embedding field (`type: "autoEmbed"`) is required. To pre-filter queries, add one or more optional `filter` fields (each with its own `type` and `path`):

| Field | Required | Description |
|---|---|---|
| `type` | Yes | `"autoEmbed"` for the embedding field, or `"filter"` for an optional filter field |
| `modality` | Yes (autoEmbed) | Must be `"text"` (only text is supported currently) |
| `path` | Yes | For an `autoEmbed` field, the document field containing the text to embed; for a `filter` field, the field to filter on |
| `model` | Yes (autoEmbed) | The Voyage AI embedding model to use |

### Examples

**Minimal index (no filters):**
```javascript
{
  "fields": [
    {
      "type": "autoEmbed",
      "modality": "text",
      "path": "description",
      "model": "voyage-4"
    }
  ]
}
```

**With filter fields (recommended for scoped search):**
```javascript
{
  "fields": [
    {
      "type": "autoEmbed",
      "modality": "text",
      "path": "description",
      "model": "voyage-4"
    },
    {
      "type": "filter",
      "path": "category"
    },
    {
      "type": "filter",
      "path": "year"
    }
  ]
}
```

### Creating the Index (mongosh)

```javascript
db.movies.createSearchIndex(
  "<index-name>",
  "vectorSearch",
  {
    "fields": [
      {
        "type": "autoEmbed",
        "modality": "text",
        "path": "<text-field>",
        "model": "voyage-4"
      }
    ]
  }
)
```

**Note:** After creation, MongoDB performs an initial sync — generating embeddings for all existing documents. This can take several hours for large collections. Monitor progress via Atlas → Search & Vector Search.

## Query Construction

### Key Difference from Manual Vector Search

With Automated Embedding, you use **`query`** (a text string) instead of **`queryVector`** (an array of numbers). MongoDB generates the query embedding automatically.

### Basic Query Syntax

```javascript
db.collection.aggregate([
  {
    $vectorSearch: {
      index: "<index-name>",
      path: "<text-field>",
      query: "<your search text>",    // Plain text — no vector needed
      numCandidates: 100,
      limit: 10
    }
  },
  {
    $project: {
      _id: 0,
      description: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

### Query with Pre-filtering

```javascript
db.collection.aggregate([
  {
    $vectorSearch: {
      index: "<index-name>",
      path: "<text-field>",
      query: "your search text",
      filter: {
        $and: [
          { category: { $eq: "electronics" } },
          { year: { $gte: 2022 } }
        ]
      },
      numCandidates: 150,
      limit: 10
    }
  },
  {
    $project: {
      _id: 0,
      description: 1,
      category: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

### Optional: Override the Query Model

You can specify a different (but compatible) embedding model at query time:

```javascript
{
  $vectorSearch: {
    index: "<index-name>",
    path: "<text-field>",
    query: "your search text",
    model: "voyage-4-lite",    // Must be compatible with the index model
    numCandidates: 100,
    limit: 10
  }
}
```

### Item-to-Item Similarity

For "given item A, find similar items" requests (e.g. "more movies like The Firm"), remember that `query` accepts **only a plain text string** — there is no raw-vector read path to reuse an existing document's stored embedding for an `autoEmbed` index.

Resolve the source item to its indexed text field first, then pass that text as the query:

```javascript
// 1. Fetch the source item's text (the same field indexed as autoEmbed)
const source = db.movies.findOne(
  { title: "The Firm" },
  { projection: { plot: 1 } }
);

// 2. Use that text as the query
db.movies.aggregate([
  {
    $vectorSearch: {
      index: "<index-name>",
      path: "plot",
      query: source.plot,           // the source item's text, not its title
      filter: { _id: { $ne: source._id } },   // exclude the item itself
      numCandidates: 100,
      limit: 10
    }
  }
])
```

Filter fields must generally be indexed as `type: "filter"` (see the index definition above). `_id` is the one exception — it is implicitly filterable on every `autoEmbed` index, so the self-exclusion `filter` above works without declaring `_id` as a filter field.

Passing the item's name (e.g. `query: "The Firm"`) searches for text semantically near that string, not near the item's actual content — pass the content field instead.

### Query Parameters Reference

| Parameter | Required | Description |
|---|---|---|
| `index` | Yes | Name of the autoEmbed vector search index |
| `path` | Yes | The field indexed as `autoEmbed` |
| `query` | Yes (with autoEmbed) | Plain text query string |
| `numCandidates` | Yes (for ANN) | Candidates to evaluate; recommend 20x `limit` |
| `limit` | Yes | Number of results to return |
| `filter` | No | MQL pre-filter; field must be indexed as `filter` type (except `_id`, which is always filterable) |
| `model` | No | Override query embedding model (must be compatible) |
| `exact` | No | `true` for ENN (exact search), omit for ANN |

**Note:** Each query call counts against your Automated Embedding rate limits because it triggers an embedding API call.

## How It Works Internally

### Initial Sync
1. MongoDB scans all documents in the collection for the indexed text field
2. Sends text to the Voyage AI model in batches (uses Flex inference tier — no standard rate limits)
3. Stores embeddings in an internal reserved database: `__mdb_internal_search`
4. Builds the vector index from the stored embeddings

### Ongoing Updates (via Change Streams)
- **Insert**: New doc detected → embedding generated → stored → index updated
- **Update**: Changed field detected → new embedding generated → old one replaced → index updated
- **Delete**: Doc deleted → embeddings removed → index updated
- Updates to non-indexed fields do **not** trigger embedding regeneration

### Embeddings Storage
Stored in `__mdb_internal_search` (internal namespace — **do not modify this database**).

Each stored document has:
```javascript
{
  _id: <same as source document>,
  <filter-field>: <copied from source>,
  _autoEmbed: {
    "<fieldPath>": [<embedding vector>]
  }
}
```

## Billing and Free Tokens

**Token consumption occurs during:**
- Index creation (initial sync)
- Document inserts and updates
- Every query (embedding generated per query)

**Free allocation:** 200M tokens per model, per organization. One-time, does not refresh. Shared across all projects and clusters. See [Model Selection](#model-selection) above for per-model pricing after free tokens are used.

**View usage:** Atlas → Search & Vector Search → Automated Embedding → Usage

**View invoices:** Atlas → Billing → Invoices (broken down by model)

**M0 clusters:** When free tokens run out, MongoDB automatically invoices for additional usage — index builds and queries do not stop. M0 users can add a payment method without upgrading their cluster: Atlas → Billing → Payment Method. Charges are for embedding model usage only.

## Rate Limits

Rate limits are enforced at the **cluster level**, shared across all autoEmbed indexes on that cluster. They are applied **separately** for queries, index inserts/updates, and initial builds.

### Initial Index Build
No standard rate limits — uses a separate inference tier optimized for throughput, with dynamic scaling up to available GPU capacity, fair resource sharing between competing index builds, and safe ramp-up from low concurrency.

**Best practice:** create the index on a prepopulated collection rather than an empty one — the initial sync benefits from this unbounded throughput, while steady-state inserts/updates afterward are subject to the rate limits below.

### Index Insert/Update Rate Limits (all tiers)

| Model | RPM | TPM |
|---|---|---|
| `voyage-4-large` | 2,000 | 3,000,000 |
| `voyage-4` | 2,000 | 8,000,000 |
| `voyage-4-lite` | 2,000 | 16,000,000 |
| `voyage-code-4` | 2,000 | 3,000,000 |
| `voyage-code-3` | 2,000 | 3,000,000 |

**Best practice:** space out bulk insert/update operations rather than sending them all at once — batching avoids hitting these per-minute limits.

### Query Rate Limits

**Free cluster (M0 without a payment method) — all models:**

| Model | RPM | TPM |
|---|---|---|
| `voyage-4-large` | 3 | 2,000 |
| `voyage-4` | 3 | 2,000 |
| `voyage-4-lite` | 3 | 2,000 |
| `voyage-code-4` | 3 | 2,000 |
| `voyage-code-3` | 3 | 2,000 |

**Paid cluster (M0 with a payment method, Flex, or M10+ dedicated):**

| Model | RPM | TPM |
|---|---|---|
| `voyage-4-large` | 2,000 | 3,000,000 |
| `voyage-4` | 2,000 | 8,000,000 |
| `voyage-4-lite` | 2,000 | 16,000,000 |
| `voyage-code-4` | 2,000 | 3,000,000 |
| `voyage-code-3` | 2,000 | 3,000,000 |

Paid-tier limits increase automatically as usage grows over time — no action needed to benefit from that growth.

**If rate limits are hit:**
- Inserts/updates: queued and retried automatically with exponential backoff
- Queries: return an error — application must handle and retry
- Free cluster hitting the 3 RPM ceiling: add a payment method to upgrade to paid-tier limits (Atlas → Billing → Payment Method) — this alone raises the ceiling from 3 to 2,000 RPM (~667x), with a correspondingly higher TPM allowance
- Paid tier still hitting limits: contact MongoDB Support for a limit increase

## Management and Monitoring

### View Usage (Atlas)
Atlas → Search & Vector Search page → Automated Embedding → Usage

Shows:
- Total tokens used and remaining free tokens
- Usage breakdown by model
- Usage breakdown by operation (indexing vs querying)

### View Rate Limits (Atlas)
Atlas → Search & Vector Search page → Automated Embedding → Rate Limits

### View Organization-Level Usage
Atlas → Organization level → AI Models → Usage

### Disable Automated Embedding (Organization Policy)
Use Atlas Resource Policies with Cedar syntax.

**Disable entirely:**
```
forbid (
  principal,
  action == ResourcePolicy::Action::"search.index.modify",
  resource
) when {
  context.search.index.isAutoEmbed
};
```

**Disable with project-level exceptions** (replace `<project-id-1>`/`<project-id-2>` with actual project IDs):
```
forbid (
  principal,
  action == ResourcePolicy::Action::"search.index.modify",
  resource
) when {
  context.search.index.isAutoEmbed
} unless {
  resource in ResourcePolicy::Project::"<project-id-1>" ||
  resource in ResourcePolicy::Project::"<project-id-2>"
};
```

Apply at: Atlas → Organization Settings → Resource Policies → Create policy

**Note:** this policy blocks new `autoEmbed` indexes going forward. Existing `autoEmbed` indexes must be deleted manually to bring a project into compliance.

## Troubleshooting

**Index stuck in Building state / initial sync taking a long time**
- Normal for large collections — initial sync can take hours
- Monitor via Atlas → Search & Vector Search → index status
- Check token consumption hasn't exceeded rate limits

**Query returns `context-limit-exceeded` error**
- Your query text exceeds 32,000 tokens (the model context window)
- Truncate or shorten your query text before passing it to `$vectorSearch`

**Queries return rate limit error**
- You've exceeded your query RPM or TPM
- Free tier users: add a payment method to upgrade to paid limits
- Paid tier users: contact MongoDB Support for a limit increase
- Short term: implement retry with backoff in your application

**No results returned**
- Check the index status is `READY` (not `Building` or `Failed`)
- Verify the `path` in the query matches the `path` in the index definition
- Verify the `index` name matches exactly (typos return no results silently)

**Missing embeddings for some documents**
- Documents inserted before the index was created are synced during initial sync — check if sync is still in progress
- Documents without the indexed text field are skipped (no embedding generated)

**`__mdb_internal_search` database appearing in Data Explorer**
- This is normal — it's the internal storage for generated embeddings
- Do not modify or delete collections in this database
hybrid-search.md 23.1 KB
# Hybrid Search

**Scope**: This guide covers hybrid search patterns in MongoDB Atlas: combining vector and lexical search using `$rankFusion` and `$scoreFusion`, and using lexical prefilters with the `vectorSearch` operator inside `$search`. For pure vector search indexes and `$vectorSearch` query construction, see `vector-search.md`. For lexical index definitions and query patterns, see `lexical-search-indexing.md` and `lexical-search-querying.md`. For automated embedding (`autoEmbed`) index and query syntax used inside a hybrid pipeline, see `automated-embedding.md`.

## Table of Contents

- [Overview](#overview)
- [Choosing the Right Approach](#choosing-the-right-approach)
- [Indexing for Hybrid Search](#indexing-for-hybrid-search)
- [$rankFusion](#rankfusion)
- [$scoreFusion](#scorefusion)
- [Lexical Prefilters (vectorSearch Operator)](#lexical-prefilters-vectorsearch-operator)
- [Best Practices and Limitations](#best-practices-and-limitations)

---

## Overview

Hybrid search combines multiple search methods on the same collection and merges the results into a single ranked or scored list.

**Three patterns covered in this guide:**

| Pattern | Stage / Operator | Use When |
|---|---|---|
| Rank-based fusion | `$rankFusion` | Document position matters; use RRF algorithm |
| Score-based fusion | `$scoreFusion` | Score magnitude matters; need custom math or normalization |
| Lexical prefilter | `$search` + `vectorSearch` operator | Need fuzzy/phrase/wildcard/compound pre-filtering before vector search |

**$rankFusion vs $scoreFusion:**
- `$rankFusion` ranks by position in each input pipeline using the Reciprocal Rank Fusion (RRF) algorithm. A document ranked #1 in multiple pipelines scores much higher than one ranked #1 in only one. Weights influence how much each pipeline's rank contributes.
- `$scoreFusion` ranks by the actual score values from each pipeline. Supports normalization (sigmoid, minMaxScaler) and custom combination expressions. Use when score magnitude, not just ordering, matters.

---

## Choosing the Right Approach

| Scenario | Recommended Approach |
|---|---|
| Combine lexical + vector, rank by position | `$rankFusion` |
| Combine lexical + vector, control score math or normalization | `$scoreFusion` |
| Multiple query vectors or embedding models on same collection | `$rankFusion` with multiple `$vectorSearch` pipelines |
| Pre-filter vector search with fuzzy, phrase, wildcard, or compound | `$search` + `vectorSearch` operator |
| Pre-filter vector search with simple equality or range | `filter` fields in `$vectorSearch` (see vector-search.md) |
| Cross-collection hybrid search | `$unionWith` + `$vectorSearch` (not `$rankFusion`/`$scoreFusion`) |
| Combine lexical + semantic search without writing embedding code | `$rankFusion` or `$scoreFusion` with an `autoEmbed`-type `$vectorSearch` pipeline (see automated-embedding.md) |

**Version requirements**: `$rankFusion` requires MongoDB 8.0+. `$scoreFusion` requires MongoDB 8.3+. Only proceed with this guide if the use case is lexical prefilters, or if the cluster meets the version requirement for the fusion stage of interest. Otherwise do not proceed — inform the user the feature is unavailable and suggest upgrading, and offer to help them build the individual lexical or vector search components separately in the meantime.

---

## Indexing for Hybrid Search

### For $rankFusion and $scoreFusion

You need two separate indexes on the collection:

**1. A vectorSearch-type index** for the `$vectorSearch` input pipeline:
```javascript
db.collection.createSearchIndex(
  "<vector-index-name>",
  "vectorSearch",
  {
    "fields": [
      {
        "type": "vector",
        "path": "<embedding-field>",
        "numDimensions": <number>,
        "similarity": "dotProduct"
      }
    ]
  }
)
```

**2. A search-type index** for the `$search` input pipeline:
```javascript
db.collection.createSearchIndex(
  "<search-index-name>",
  {
    "mappings": { "dynamic": true }
  }
)
```

**Using automated embedding instead:** If you want MongoDB to generate and manage the embeddings rather than supplying your own, create an `autoEmbed`-type vectorSearch index instead of the `vector`-type index shown above. See `automated-embedding.md` for the index definition and query syntax — the fusion-stage rules below apply the same way regardless of which index type backs the vector pipeline.

---

### For Lexical Prefilters (vectorSearch Operator)

The `vectorSearch` operator runs inside `$search`, so you need a **single search-type index** that includes a `vector` field type. This is different from a vectorSearch-type index — you cannot use the `$vectorSearch` stage to query fields indexed this way.

```javascript
db.collection.createSearchIndex(
  "<search-index-name>",
  {
    "mappings": {
      "dynamic": true,
      "fields": {
        "<embedding-field>": {
          "type": "vector",
          "numDimensions": <number>,
          "similarity": "dotProduct",
          "quantization": "scalar"  // Optional
        }
      }
    }
  }
)
```

**Note**: `storedSource: true` is not supported on indexes that contain a `vector` field type. Use `include` or `exclude` to specify stored fields explicitly.

---

## Common Rules for Fusion Stages

The following rules apply to both `$rankFusion` and `$scoreFusion`.

**Pipeline naming restrictions**: Pipeline names must not be empty, start with `$`, contain the null character `\0`, or contain `.`

**Not allowed inside input pipelines**: `$project` or `storedSource` fields. Apply modifications (`$project`, `$addFields`, `$set`) in stages after the fusion stage.

---

## $rankFusion

`$rankFusion` executes all input pipelines independently, de-duplicates results, and ranks them using the Reciprocal Rank Fusion (RRF) algorithm. Documents appearing highly ranked in multiple pipelines score highest.

### Syntax

```javascript
{
  $rankFusion: {
    input: {
      pipelines: {
        <pipelineName1>: [ <stages> ],
        <pipelineName2>: [ <stages> ],
        ...
      }
    },
    combination: {
      weights: {
        <pipelineName1>: <number>,
        <pipelineName2>: <number>
      }
    },
    scoreDetails: <boolean>  // Default: false
  }
}
```

### Fields

| Field | Type | Description |
|---|---|---|
| `input.pipelines` | Object | Map of pipeline names to aggregation stages. At least one required. |
| `combination.weights` | Object | Optional. Per-pipeline weights (non-negative numbers). Default weight is 1. |
| `scoreDetails` | Boolean | Optional. If true, populates `$meta: "scoreDetails"` per document. Default false. |

### RRF Formula

For each document, the RRF score is:

```
RRFscore(d) = sum over all pipelines of: weight * (1 / (60 + rank_of_d_in_pipeline))
```

The constant 60 is a sensitivity parameter set by MongoDB and cannot be changed. Documents not present in a pipeline do not contribute a term for that pipeline.

### Input Pipeline Restrictions

See [Common Rules](#common-rules-for-fusion-stages) for naming and modification restrictions. Allowed stages: `$search`, `$vectorSearch`, `$match`, `$geoNear`, `$sample`, `$sort`, `$skip`, `$limit`.

The ordering requirement is satisfied if the pipeline begins with `$search`, `$vectorSearch`, or `$geoNear`, or contains an explicit `$sort`.

---

### Example 1: Basic Hybrid (Vector + Lexical, Equal Weights)

```javascript
db.embedded_movies.aggregate([
  {
    $rankFusion: {
      input: {
        pipelines: {
          vectorPipeline: [
            {
              $vectorSearch: {
                index: "<vector-index-name>",
                path: "plot_embedding",
                queryVector: [<query-vector-2048-dimensions>],
                numCandidates: 100,
                limit: 20
              }
            }
          ],
          textPipeline: [
            {
              $search: {
                index: "<search-index-name>",
                text: {
                  query: "<query-term>",
                  path: "title"
                }
              }
            },
            { $limit: 20 }
          ]
        }
      }
    }
  },
  { $limit: 10 }
])
```

**Note**: `$search` does not auto-limit results — always add `$limit` inside the `$search` input pipeline.

---

### Example 2: Weighted Hybrid (Boosting One Pipeline)

Assign higher weight to the pipeline whose ranking should contribute more to the final score:

```javascript
db.embedded_movies.aggregate([
  {
    $rankFusion: {
      input: {
        pipelines: {
          vectorPipeline: [
            {
              $vectorSearch: {
                index: "<vector-index-name>",
                path: "plot_embedding",
                queryVector: [<query-vector-2048-dimensions>],
                numCandidates: 100,
                limit: 20
              }
            }
          ],
          textPipeline: [
            {
              $search: {
                index: "<search-index-name>",
                phrase: {
                  query: "<query-term>",
                  path: "title"
                }
              }
            },
            { $limit: 20 }
          ]
        }
      },
      combination: {
        weights: {
          vectorPipeline: 0.7,
          textPipeline: 0.3
        }
      }
    }
  },
  { $limit: 10 }
])
```

**Recommendation**: Set weights per-query based on which method is more appropriate for that query, rather than using static weights for all queries.

---

### Example 3: Multiple $vectorSearch Pipelines

Use multiple vector pipelines to search different fields, different query vectors, or different embedding models:

```javascript
db.embedded_movies.aggregate([
  {
    $rankFusion: {
      input: {
        pipelines: {
          plotPipeline: [
            {
              $vectorSearch: {
                index: "<vector-index-name>",
                path: "plot_embedding_voyage",
                queryVector: [<query-vector-2048-dimensions>],
                numCandidates: 200,
                limit: 50
              }
            }
          ],
          titlePipeline: [
            {
              $vectorSearch: {
                index: "<vector-index-name>",
                path: "title_embedding_voyage",
                queryVector: [<query-vector-2048-dimensions>],
                numCandidates: 200,
                limit: 50
              }
            }
          ]
        }
      },
      combination: {
        weights: {
          plotPipeline: 0.5,
          titlePipeline: 0.5
        }
      }
    }
  },
  { $limit: 20 }
])
```

---

### Example 4: Automated Embedding (autoEmbed) + Lexical Search

If the vector pipeline targets an `autoEmbed`-type index, pass plain text via `query` instead of a numeric array via `queryVector` — MongoDB generates the embedding automatically:

```javascript
db.movies.aggregate([
  {
    $rankFusion: {
      input: {
        pipelines: {
          semanticPipeline: [
            {
              $vectorSearch: {
                index: "<autoembed-index-name>",
                path: "<text-field>",
                query: "<query-text>",    // Plain text — no embedding vector needed
                numCandidates: 100,
                limit: 20
              }
            }
          ],
          textPipeline: [
            {
              $search: {
                index: "<search-index-name>",
                text: {
                  query: "<query-term>",
                  path: "<text-field>"
                }
              }
            },
            { $limit: 20 }
          ]
        }
      },
      combination: {
        weights: {
          semanticPipeline: 0.7,
          textPipeline: 0.3
        }
      }
    }
  },
  { $limit: 10 }
])
```

The only difference from Example 2 is the vector pipeline's `query` field: it takes a text string instead of a `queryVector` array. Weighting, the `$limit` inside `$search`, and RRF scoring all work identically. See `automated-embedding.md` for model selection and index setup.

---

### Surfacing scoreDetails

Set `scoreDetails: true` on the stage, then project via `$meta: "scoreDetails"`. The output includes a `value` (final RRF score), `description`, and a `details` array — one entry per input pipeline — containing `inputPipelineName`, `rank`, `weight`, and optionally `value` (raw pipeline score). See the `$scoreFusion` scoreDetails section below for a concrete structure example; `$rankFusion` follows the same pattern with `rank` instead of `inputPipelineRawScore`.

---

## $scoreFusion

`$scoreFusion` executes all input pipelines independently, de-duplicates results, and combines them using the actual score values from each pipeline. Supports normalization and custom combination expressions for fine-grained control over how scores are merged.

### Syntax

```javascript
{
  $scoreFusion: {
    input: {
      pipelines: {
        <pipelineName1>: [ <stages> ],
        <pipelineName2>: [ <stages> ],
        ...
      },
      normalization: "none | sigmoid | minMaxScaler"
    },
    combination: {
      weights: {
        <pipelineName1>: <number>,
        <pipelineName2>: <number>
      },
      method: "avg | expression",
      expression: <arithmetic-expression>
    },
    scoreDetails: <boolean>
  }
}
```

### Fields

| Field | Type | Description |
|---|---|---|
| `input.pipelines` | Object | Map of pipeline names to aggregation stages. At least one required. |
| `input.normalization` | String | Normalize scores before combining: `none` (no normalization), `sigmoid`, or `minMaxScaler`. |
| `combination.weights` | Object | Optional. Per-pipeline weights applied to normalized scores. Default is 1. Mutually exclusive with `combination.expression`. |
| `combination.method` | String | `avg` (default) or `expression`. |
| `combination.expression` | Expression | Custom arithmetic expression. Use pipeline names as variables representing each pipeline's score. Mutually exclusive with `combination.weights`. |
| `scoreDetails` | Boolean | Optional. If true, populates `$meta: "scoreDetails"` per document. Default false. |

### Normalization Options

| Option | Effect |
|---|---|
| `none` | No normalization — raw scores combined as-is |
| `sigmoid` | Applies the sigmoid expression, mapping scores to (0, 1) |
| `minMaxScaler` | Applies the minMaxScaler window operator, scaling scores to [0, 1] |

### Input Pipeline Restrictions

See [Common Rules](#common-rules-for-fusion-stages) for naming and modification restrictions. Allowed stages: `$search`, `$vectorSearch`, `$match`, `$geoNear`, `$sort`, `$skip`, `$limit`. Note: unlike `$rankFusion`, `$sample` is not permitted.

The scoring requirement is satisfied if the pipeline begins with `$search`, `$vectorSearch`, `$match` with legacy text search, or `$geoNear`. Otherwise, include an explicit `$score` stage.

---

### Example 1: avg Method with Weights

```javascript
db.embedded_movies.aggregate([
  {
    $scoreFusion: {
      input: {
        pipelines: {
          vectorPipeline: [
            {
              $vectorSearch: {
                index: "<vector-index-name>",
                path: "plot_embedding",
                queryVector: [<query-vector-2048-dimensions>],
                numCandidates: 100,
                limit: 20
              }
            }
          ],
          textPipeline: [
            {
              $search: {
                index: "<search-index-name>",
                text: {
                  query: "<query-term>",
                  path: "title"
                }
              }
            },
            { $limit: 20 }
          ]
        },
        normalization: "sigmoid"
      },
      combination: {
        method: "avg",
        weights: {
          vectorPipeline: 2,
          textPipeline: 1
        }
      }
    }
  },
  { $limit: 10 }
])
```

---

### Example 2: expression Method with Custom Score Math

Use `expression` when you need full control over how pipeline scores are combined. Reference pipeline names as variables in the expression:

```javascript
db.embedded_movies.aggregate([
  {
    $scoreFusion: {
      input: {
        pipelines: {
          searchOne: [
            {
              $vectorSearch: {
                index: "<vector-index-name>",
                path: "plot_embedding",
                queryVector: [<query-vector-2048-dimensions>],
                numCandidates: 100,
                limit: 20
              }
            }
          ],
          searchTwo: [
            {
              $search: {
                index: "<search-index-name>",
                text: {
                  query: "<query-term>",
                  path: "title"
                }
              }
            },
            { $limit: 20 }
          ]
        },
        normalization: "sigmoid"
      },
      combination: {
        method: "expression",
        expression: {
          $sum: [
            { $multiply: ["$searchOne", 10] },
            "$searchTwo"
          ]
        }
      },
      scoreDetails: true
    }
  },
  {
    $project: {
      _id: 1,
      title: 1,
      plot: 1,
      scoreDetails: { $meta: "scoreDetails" }
    }
  },
  { $limit: 10 }
])
```

**Note**: `combination.expression` and `combination.weights` are mutually exclusive. When using `expression`, embed weights directly via `$multiply` as shown above.

---

**Using autoEmbed pipelines:** As with `$rankFusion`, pass `query` (text) instead of `queryVector` (array) in the `$vectorSearch` stage when it targets an `autoEmbed`-type index — see [Example 4 under $rankFusion](#example-4-automated-embedding-autoembed--lexical-search) and `automated-embedding.md` for the full syntax.

---

### Surfacing scoreDetails

Set `scoreDetails: true`, then use `$meta: "scoreDetails"` in `$project`, `$addFields`, or `$set`:

```javascript
{
  $project: {
    title: 1,
    scoreDetails: { $meta: "scoreDetails" }
  }
}
```

**scoreDetails structure:**
```javascript
{
  value: 7.847,
  description: "the value calculated by combining the scores...",
  normalization: "sigmoid",
  combination: {
    method: "custom expression",
    expression: "{ $sum: [{ $multiply: ['$searchOne', 10] }, '$searchTwo'] }"
  },
  details: [
    {
      inputPipelineName: "searchOne",
      inputPipelineRawScore: 0.798,
      weight: 1,
      value: 0.689,
      details: []
    },
    {
      inputPipelineName: "searchTwo",
      inputPipelineRawScore: 2.962,
      weight: 1,
      value: 0.950,
      details: []
    }
  ]
}
```

---

## Lexical Prefilters (vectorSearch Operator)

The `vectorSearch` operator runs inside a `$search` stage and performs ANN or ENN vector search with the ability to pre-filter using any Atlas Search operator — including `text` with fuzzy matching, `phrase`, `wildcard`, `queryString`, and `compound`. This is more expressive than the MQL-only `filter` option in the `$vectorSearch` stage.

**Requires**: A `search`-type index (not vectorSearch-type) with the embedding field configured as `vector` type. See [Indexing for Hybrid Search](#indexing-for-hybrid-search).

**Cannot be used**: Inside `embeddedDocument`, `compound`, or `facet` operators.

### Syntax

```javascript
{
  $search: {
    index: "<search-index-name>",
    vectorSearch: {
      path: "<vector-field>",
      queryVector: [<array-of-numbers>],
      limit: <number>,
      numCandidates: <number>,       // Required for ANN (exact: false)
      exact: true | false,           // Optional, default false
      filter: { <search-operator> }, // Optional
      score: { <score-options> }     // Optional
    },
    concurrent: true  // Optional, dedicated search nodes only
  }
}
```

### Key Fields

| Field | Required | Description |
|---|---|---|
| `path` | Yes | The field indexed as `vector` type in the search index |
| `queryVector` | Yes | Array of numbers matching `numDimensions` in the index |
| `limit` | Yes | Number of results to return |
| `numCandidates` | Conditional | Required if `exact` is false or omitted. Max 10000. Recommend 20x `limit`. |
| `exact` | No | `true` for ENN, `false`/omit for ANN |
| `filter` | No | Any Atlas Search operator to pre-filter documents |
| `concurrent` | No | Parallelizes search across segments on dedicated search nodes. Ignored if no dedicated search nodes. |

---

### Example 1: compound Prefilter (queryString + range)

Filter by text match OR date range before running vector search:

```javascript
db.embedded_movies.aggregate([
  {
    $search: {
      index: "<search-index-name>",
      vectorSearch: {
        path: "plot_embedding",
        queryVector: [<query-vector-2048-dimensions>],
        limit: 10,
        exact: true,
        filter: {
          compound: {
            should: [
              {
                queryString: {
                  defaultPath: "fullplot",
                  query: "plot:courtroom OR lawyer"
                }
              },
              {
                range: {
                  path: "year",
                  gte: 2000,
                  lte: 2015
                }
              }
            ]
          }
        }
      },
      concurrent: true
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      score: { $meta: "searchScore" }
    }
  }
])
```

---

### Example 2: text Prefilter with Fuzzy Matching

Filter by fuzzy text match before running ANN vector search:

```javascript
db.embedded_movies.aggregate([
  {
    $search: {
      index: "<search-index-name>",
      vectorSearch: {
        path: "plot_embedding",
        queryVector: [<query-vector-2048-dimensions>],
        limit: 10,
        numCandidates: 200,
        filter: {
          text: {
            path: "fullplot",
            query: "charming animal",
            fuzzy: {}
          }
        }
      },
      concurrent: true
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      score: { $meta: "searchScore" }
    }
  }
])
```

---

## Best Practices and Limitations

### Best Practices

**Set limits inside $search sub-pipelines**: `$search` does not limit results by default. Always add `$limit` inside the input pipeline, or `$rankFusion`/`$scoreFusion` evaluates all search results.

```javascript
textPipeline: [
  { $search: { ... } },
  { $limit: 20 }  // Required
]
```

**Set weights per-query**: Tune weights based on which search method is most appropriate for a given query rather than using fixed weights for all queries. This improves relevance and resource utilization.

**Handle disjoint results**: If most results come from one pipeline and not the other, the two methods are returning largely different documents. Increase per-pipeline limits to improve overlap.

**Use `$match` for non-search filtering**: To filter on specific fields without a search pipeline (e.g., boost on a flag field), add a `$match` pipeline inside `input.pipelines`. It must contain an explicit `$sort` to qualify as a ranked pipeline.

### Limitations

**Single collection only**: `$rankFusion` and `$scoreFusion` cannot span multiple collections. For cross-collection hybrid search, use `$unionWith` with `$vectorSearch`.

**Pipelines run serially**: Input pipelines do not execute in parallel.

**No pagination inside sub-pipelines**: `$rankFusion` and `$scoreFusion` do not support pagination within input pipelines.

**vectorSearch operator restrictions**: Cannot be used inside `embeddedDocument`, `compound`, or `facet` operators. Cannot use `highlight`, `sort`, or `searchSequenceToken` with the `vectorSearch` operator — use `$skip` and `$limit` after `$search` instead.
lexical-search-indexing.md 19.5 KB
# Lexical Search - Indexing

This guide covers how to configure MongoDB Atlas Search indexes. Use this reference to build index definitions with proper field types, analyzers, mappings, and optimization settings.

## Table of Contents

- [Atlas Search Index Definition](#atlas-search-index-definition)
- [Analyzer Selection](#analyzer-selection)
- [Field Types](#field-types)
- [Dynamic vs Explicit Mappings](#dynamic-vs-explicit-mappings)
- [Stored Source](#stored-source)
- [Synonyms](#synonyms)

---

## Atlas Search Index Definition

### Syntax

```javascript
{
  "analyzer": "<analyzer-for-index>",
  "searchAnalyzer": "<analyzer-for-query>",
  "mappings": {
    "dynamic": <boolean> | {
      "typeSet": "<typeSet-name>"
    },
    "fields": {
      <field-definition>
    }
  },
  "numPartitions": <integer>,
  "analyzers": [ <custom-analyzer> ],
  "storedSource": <boolean> | {
    <stored-source-definition>
  },
  "synonyms": [
    {
      <synonym-mapping-definition>
    }
  ],
  "typeSets": [
    {
      "types": [
        {<field-types-definition>}
      ]
    }
  ]
}
```

### Options

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `analyzer` | String | Optional | Specifies the analyzer to apply to string fields when indexing. If set only at the top level and not specified for individual fields, applies to all fields. If omitted, defaults to Standard Analyzer. |
| `searchAnalyzer` | String | Optional | Specifies the analyzer to apply to query text before searching. If omitted, defaults to the `analyzer` option. If both omitted, defaults to Standard Analyzer. |
| `mappings` | Object | Required | Specifies how to index fields at different paths for this index. |
| `mappings.dynamic` | Boolean or Object | Optional | Enables dynamic mapping of field types or configures fields individually. Set to `true` to recursively index all indexable field types, `false` to only index fields specified in `mappings.fields`, or specify a `typeSet` for configurable dynamic indexing. If omitted, defaults to `false`. **Note:** Dynamic indexing automatically and recursively indexes all nested documents unless explicitly disabled. |
| `mappings.dynamic.typeSet` | String | Optional | References the name of the `typeSets` object that contains the list of field types to automatically and recursively index. Mutually exclusive with `mappings.dynamic` boolean flag. |
| `mappings.fields` | Object | Conditional | Specifies the fields that you want to index. Required only if `dynamic` is `false`. You can't index fields that contain the dollar ($) sign at the start of the field name. |
| `numPartitions` | Integer | Optional | Specifies the number of sub-indexes to create if the document count exceeds two billion. Valid values: 1, 2, 4. If omitted, defaults to 1. Requires search nodes deployed in your cluster. |
| `analyzers` | Array of Custom Analyzers | Optional | Specifies the custom analyzers to use in this index. Reference by name in `analyzer`, `searchAnalyzer`, or field-level analyzer options. |
| `storedSource` | Boolean or Object | Optional | Specifies fields in documents to store for query-time look-ups using `returnStoredSource`. Can be `true` (store all fields), `false` (store no fields), or an object specifying fields to include/exclude. Available on clusters running MongoDB 7.0+. If omitted, defaults to `false`. |
| `synonyms` | Array of Synonym Mapping Definition | Optional | Specifies synonym mappings to use in your index. An index definition can have only one synonym mapping. |
| `typeSets` | Array of Objects | Optional | Specifies the typeSets to use for dynamic mappings. |
| `typeSets.[n].name` | String | Required | Specifies the name of the typeSet configuration. |
| `typeSets.[n].types` | Array of Objects | Required | Specifies the field types to index automatically using dynamic mappings. |
| `typeSets.[n].types.[n].type` | String | Required | Specifies the field type to automatically index (e.g., "string", "number", "date"). |

### Basic Definition

Most indexes only need the mappings configuration:

```javascript
{
  "mappings": {
    "dynamic": <boolean> | { <typeSet-definition> },
    "fields": { <field-definition> }
  }
}
```

---

## Analyzer Selection

The analyzer determines how text is processed for indexing and searching.

**Default behavior:** Most queries don't specify an analyzer and use MongoDB's default **standard analyzer**, which:
- Divides text into terms based on word boundaries (language-neutral)
- Converts terms to lowercase and removes punctuation
- Recognizes email addresses, acronyms, CJK characters, alphanumerics, and more

**Common built-in analyzers:**

| Analyzer | Use Case | Example |
|----------|----------|---------|
| `lucene.standard` | General text search (default) | "The quick brown fox" → ["quick", "brown", "fox"] |
| `lucene.simple` | Lowercase, no special chars | "Hello-World!" → ["hello", "world"] |
| `lucene.keyword` | Exact matching, facets | "Action" → ["Action"] |
| `lucene.whitespace` | Split on spaces only | "first-class" → ["first-class"] |
| Language-specific | Stemming, stop words | `lucene.english`, `lucene.spanish` |

---

### Index Analyzer (Applied at Index Time)

Specify per-field or top-level for all fields:

```javascript
// Field-level (add to mappings.fields):
{
  "title": {
    "type": "string",
    "analyzer": "lucene.standard"  // Or omit to use default
  },
  "category": {
    "type": "token"   // Exact matching — use token, not string with lucene.keyword
  }
}

// Top-level (applies to all fields unless overridden):
{
  "analyzer": "lucene.standard",
  "mappings": {
    "fields": {
      "title": { "type": "string" }  // Uses top-level analyzer
    }
  }
}
```

---

### Search Analyzer (Applied at Query Time)

Apply different analysis to queries than to indexed content:

```javascript
// Top-level searchAnalyzer:
{
  "searchAnalyzer": "lucene.simple",  // Query-time analyzer
  "mappings": {
    "fields": {
      "description": {
        "type": "string",
        "analyzer": "lucene.standard"  // Index-time analyzer
      }
    }
  }
}
```

**Use case:** Index with standard analysis, but search with simpler/synonym-aware analyzer.

If omitted, uses the index `analyzer`. If both omitted, defaults to `lucene.standard`.

---

### Multi Analyzer (Alternate Analyzers for Same Field)

Index the same field with multiple analyzers:

```javascript
// Field configuration (add to mappings.fields):
{
  "title": {
    "type": "string",
    "analyzer": "lucene.standard",  // Default analyzer
    "multi": {
      "keywordAnalyzer": {
        "type": "string",
        "analyzer": "lucene.keyword"  // Alternate analyzer
      }
    }
  }
}
```

**Use case:** Support both fuzzy matching and exact matching on the same field.

To query using the alternate analyzer, specify the path as `fieldName.alternateAnalyzerName` (e.g., `title.keywordAnalyzer`).

---

### Custom Analyzers

Define custom tokenization and filtering:

```javascript
// Index definition with custom analyzer:
{
  "analyzers": [
    {
      "name": "customAnalyzer",
      "tokenizer": {
        "type": "standard"
      },
      "charFilters": [],
      "tokenFilters": [
        { "type": "lowercase" },
        { "type": "stop", "tokens": ["the", "a", "an"] }
      ]
    }
  ],
  "mappings": {
    "fields": {
      "content": {
        "type": "string",
        "analyzer": "customAnalyzer"  // Reference custom analyzer
      }
    }
  }
}
```

**Use case:** Need specific tokenization or filtering not provided by built-in analyzers.

---

### Normalizers (Token Type Only)

Normalizers produce a single token (used with `token` field type):

```javascript
// Field configuration (add to mappings.fields):
{
  "username": {
    "type": "token",
    "normalizer": "lowercase"  // Options: "lowercase", "none"
  }
}
```

**Normalizers:**
- `lowercase`: Transforms to lowercase, creates single token
- `none`: No transformation, creates single token

**Use case:** Exact matching with case normalization for token fields.

---

### Decision Guide

- **lucene.standard** (or omit): Default for most text fields
- **lucene.keyword**: Categories, tags
- **Language-specific**: When you know the content language
- **searchAnalyzer**: Different analysis for queries vs indexed content (e.g., synonyms)
- **multi**: Support multiple search patterns on same field
- **Custom**: Need specific tokenization/filtering logic
- **Normalizers**: Token fields requiring case normalization

---

## Field Types

**Dynamic mapping includes:** boolean, date, number, objectId, string, uuid
**Must configure explicitly:** autocomplete, token, geo, embeddedDocuments, vector

### Quick Reference

| Type | When to Use | Required Fields | Optional Fields (with valid values) | Notes |
|------|-------------|-----------------|-------------------------------------|-------|
| **string** | Full-text search, phrase matching, fuzzy search | type | analyzer, searchAnalyzer, indexOptions: "docs" or "freqs" or "positions" or "offsets", store: true or false, multi | Default for text. For sorting use token instead. |
| **token** | Sort/facet on text, exact matching | type | normalizer: "lowercase" or "none" (default: "none") | Required for sorting or faceting strings. Max 8181 chars. |
| **autocomplete** | Search-as-you-type, typeahead, partial or substring matching | type | analyzer, tokenization: "edgeGram" or "rightEdgeGram" or "nGram" (default: "edgeGram"), minGrams (default: 2), maxGrams (default: 15), foldDiacritics: true or false | Not included in "dynamic: true". Recommend maxGrams ≤ 15. |
| **boolean** | True/false filters | type | None | Included in "dynamic: true". |
| **date** | Date ranges, timestamps | type | None | Included in "dynamic: true". |
| **number** | Numeric queries, ranges, sorting | type | representation: "int64" or "double" (default: "double"), indexIntegers: true or false, indexDoubles: true or false | Included in "dynamic: true". Use int64 for large integers. |
| **objectId** | Query by _id | type | None | Included in "dynamic: true". Standard MongoDB ObjectIds. |
| **uuid** | UUID identifiers | type | None | Included in "dynamic: true". BSON Binary Subtype 4. |
| **geo** | Location search, geographic queries | type | indexShapes: true or false (default: false) | Included in "dynamic: true". Requires GeoJSON. Set indexShapes=true for polygons. |
| **embeddedDocuments** | Search in arrays of objects, independent scoring | type | dynamic: true or false or {typeSet: "name"} (default: false), fields, storedSource: true or false or {include/exclude} | Not included in "dynamic: true". Max 5 nesting levels. Each nested document counts toward 2.1B limit. |
| **vector** | Lexical prefilters for semantic search | type, numDimensions (1-8192), similarity: "cosine" or "dotProduct" or "euclidean" | quantization: "none" or "scalar" or "binary" (default: "none"), hnswOptions.maxEdges: 16-64, hnswOptions.numEdgeCandidates: 100-3200 | Not included in "dynamic: true". For hybrid search. See vector-search.md and hybrid-search.md. |

**Field definition structure:**
```javascript
{
  "mappings": {
    "fields": {
      "<field-name>": {
        "type": "<field-type>",
        // type-specific options here
      }
    }
  }
}
```

**Multiple types on same field:**
```javascript
"<field-name>": [
  { "type": "string" },
  { "type": "token", "normalizer": "lowercase" }
]
```

**Arrays:** MongoDB Search automatically flattens arrays during indexing. Specify only the element type, not that it's an array.

---

## Dynamic vs Explicit Mappings

**Choose based on user's needs:**

**Use dynamic (true)** when:
- User is prototyping or exploring data with unknown schema
- Need to get started quickly without defining all fields
- All or most fields need to be searchable
- Accept larger index size and slower performance for convenience

**Use explicit (dynamic: false)** (recommended for production) when:
- User has completed early stages of prototyping and knows exactly which fields to search
- Performance and index size are priorities
- Schema is stable and well-defined
- Only a subset of fields need to be searchable

**Use typeSets (recommended for production)** when:
- User wants automatic indexing but with control over which types
- Document schema is dynamic and new fields need to be indexed automatically without an index rebuild
- Want different indexing strategies for different nested documents
- Balance between convenience and performance is important

---

**Dynamic mappings** automatically index all fields:
```javascript
{
  "mappings": {
    "dynamic": true  // Index everything
  }
}
```
- **Pros**: Quick setup, works immediately
- **Cons**: Larger index, slower queries, wastes resources on unused fields

**Explicit mappings** define exactly what to index:
```javascript
{
  "mappings": {
    "dynamic": false,  // Only index specified fields
    "fields": {
      "title": { "type": "string" },
      "genre": { "type": "token" }
    }
  }
}
```
- **Pros**: Smaller index, faster queries, precise control
- **Cons**: Requires knowing your schema

**Configurable dynamic with typeSets** (recommended middle ground):
```javascript
{
  "mappings": {
    "dynamic": {
      "typeSet": "customTypes"
    },
    "fields": {
      "metadata": {
        "type": "document",
        "dynamic": {
          "typeSet": "metadataTypes"
        }
      }
    }
  },
  "typeSets": [
    {
      "name": "customTypes",
      "types": [
        { "type": "string" },
        { "type": "number" }
      ]
    },
    {
      "name": "metadataTypes",
      "types": [
        {
          "type": "string",
          "analyzer": "lucene.standard"
        }
      ]
    }
  ]
}
```
- **Pros**: Automatically indexes specified field types, more control than full dynamic, can configure different typeSets for sub-documents
- **Cons**: Still indexes all fields of specified types

**Recommendation:** Use static mappings or a dynamic typeSet (within a specific path, not at the root document level) in production for optimized index size and performance.

---

## Stored Source

Store frequently accessed fields directly in the search index (mongot) to avoid full document lookups from the database. This dramatically improves query performance, especially when filtering or sorting.

**Requirements:**
- Available on clusters running MongoDB 7.0+
- Stored fields must still be indexed separately to query them
- Retrieve stored fields at query time using returnStoredSource: true (see lexical-search-querying.md)

**Syntax:**
```javascript
{
  "storedSource": true | false | {
    "include" | "exclude": ["<field-name>", ...]
  }
}
```

**Options:**

true - Store all fields in documents. Not supported if index contains vector type field. Can significantly impact performance.

false - Don't store any fields (default behavior).

{ "include": [...] } - Store only specified fields. MongoDB Search also stores _id by default. List field names or dot-separated paths.

{ "exclude": [...] } - Store all fields except specified ones.

**Examples:**

**Store specific fields:**
```javascript
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": { "type": "string" },
      "genre": { "type": "token" },
      "year": { "type": "number" },
      "rating": { "type": "number" }
    }
  },
  "storedSource": {
    "include": ["title", "genre", "year", "rating"]
  }
}
```

**Exclude specific fields:**
```javascript
{
  "storedSource": {
    "exclude": ["largeTextField", "unusedField"]
  }
}
```

**Store all fields:**
```javascript
{
  "storedSource": true
}
```

**When to use:**
- Fields used for filtering, sorting, or projection after $search
- Frequently accessed fields in search results
- When avoiding database lookups is critical for performance

**When NOT to use:**
- Very large text fields (increases index size significantly)
- Fields rarely used in queries
- When index size is a concern

**Note:** For using stored source at query time, see lexical-search-querying.md. For vector field storage considerations, see vector-search.md.

---

## Synonyms

Use when user wants query expansion with equivalent terms (e.g., "car" also finds "automobile", "vehicle").

**Agent Workflow:**

1. **Ask user to create synonym collection** in the same database as their indexed collection.

2. **Provide synonym document format** based on user's needs:

**For bidirectional synonyms** (all terms interchangeable):
```javascript
db.synonyms.insertMany([
  {
    "mappingType": "equivalent",
    "synonyms": ["car", "vehicle", "automobile"]
  },
  {
    "mappingType": "equivalent",
    "synonyms": ["happy", "joyful", "glad"]
  }
])
```

**For one-way synonyms** (input maps to synonyms only):
```javascript
db.synonyms.insertMany([
  {
    "mappingType": "explicit",
    "input": ["pants"],
    "synonyms": ["trousers", "slacks"]
  }
])
```

3. **Add synonym mapping to index definition:**

```javascript
{
  "mappings": {
    "fields": {
      "<field-name>": {
        "type": "string",
        "analyzer": "lucene.standard"  // Note the analyzer
      }
    }
  },
  "synonyms": [
    {
      "name": "<synonym-mapping-name>",
      "analyzer": "lucene.standard",  // Must match field analyzer
      "source": {
        "collection": "<synonym-collection-name>"
      }
    }
  ]
}
```

**Critical Rules:**
- Synonym mapping analyzer MUST match the field analyzer being queried
- Only one synonym mapping allowed per index
- Changes to synonym collection auto-update (no reindex needed)
- Works only with text and phrase operators

**Example:**
If user wants "car" to also find "vehicle" and "automobile":
1. Tell user to create collection: db.synonyms.insertOne({ "mappingType": "equivalent", "synonyms": ["car", "vehicle", "automobile"] })
2. Add to index with analyzer matching the field being searched
3. Queries automatically expand (user searches "car", MongoDB Search searches: car OR vehicle OR automobile)

---

## Searching on Views

**Requires MongoDB 8.0+.** Create Atlas Search indexes on Views to partially index a collection, transform documents, or support incompatible data types.

**Note**: Programmatic index creation via `mongosh`/driver methods requires **8.1+**. On 8.0, also note that queries must run against the **source collection** referencing the view's index name. On 8.1+, you can query the view directly.

**Supported view stages**: `$addFields`, `$set`, `$match` with `$expr` only.

**Key limitations**:
- Index names must be unique across source collection and all its views
- No operators producing dynamic results (e.g., `$USER_ROLES`, `$rand`)
- Queries return original source documents. Use `storedSource` to retrieve transformed fields

**Example: partial index (filter documents)**
```javascript
db.createView("movies_After2000", "movies", [
  { $match: { $expr: { $gt: ["$released", ISODate("2000-01-01")] } } }
])

db.movies_After2000.createSearchIndex(
  "after2000Index",
  { "mappings": { "dynamic": true } }
)

// 8.1+: query view directly; 8.0: query source collection using index name
db.movies_After2000.aggregate([
  { $search: { index: "after2000Index", text: { path: "title", query: "<query>" } } }
])
```

**Editing a view**: Use `collMod`. MongoDB Search auto-reindexes on view definition changes with no downtime.

**Performance**: Complex transformations slow performance. For heavy transformations consider a materialized view, or query the source collection directly.

**Troubleshooting**:
- Index goes **FAILED**: view is incompatible with Search, or source collection was removed/changed
- Index goes **STALE**: view's pipeline fails on a document. Index remains queryable while STALE; returns to READY after fixing the document or view definition
- **`$search is only valid as first stage`** error: you're on MongoDB 8.0 querying the view directly. Query the source collection instead, or upgrade to 8.1+
lexical-search-querying.md 17.4 KB
# Lexical Search - Querying

This guide covers query patterns and optimization techniques for MongoDB Atlas Search.

## Table of Contents

- [$search vs $searchMeta](#search-vs-searchmeta)
- [Query Patterns](#query-patterns)
- [Query Optimization](#query-optimization)
- [Query Performance Analysis](#query-performance-analysis)

---

## $search vs $searchMeta

Both stages must be the **first stage** in an aggregation pipeline.

| Stage | Use When |
|---|---|
| `$search` | You need matching documents, with or without metadata |
| `$searchMeta` | You only need metadata (count, facets) — no documents returned |

`$searchMeta` shares the following fields with `$search`: `index`, all operator names (e.g. `text`, `range`, `compound`), `concurrent` (parallelizes search across segments on dedicated search nodes only — ignored otherwise), and `returnStoredSource`.

---

## Query Patterns

### Operator Reference

| Operator | Description |
|---|---|
| `autocomplete` | Search-as-you-type from incomplete input |
| `compound` | Combines multiple operators into a single query |
| `embeddedDocument` | Queries fields inside arrays of objects |
| `equals` | Exact match on boolean, date, number, objectId, token, uuid |
| `exists` | Tests for presence of a field |
| `geoShape` | Queries shapes by spatial relation (geo type, indexShapes: true) |
| `geoWithin` | Queries points within a region (geo type) |
| `hasAncestor` | Queries ancestor-level fields when using `returnScope` |
| `hasRoot` | Queries root-level fields when using `returnScope` |
| `in` | Queries single values or arrays of values |
| `moreLikeThis` | Finds documents similar to a given document |
| `near` | Queries values near a number, date, or geo point |
| `phrase` | Searches for terms in a specific order |
| `queryString` | Boolean/field-specific query syntax |
| `range` | Queries values within a numeric, date, string, or objectId range |
| `regex` | Regular expression matching on string fields |
| `text` | Full-text analyzed search on string fields |
| `vectorSearch` | Semantic search with lexical pre-filters (vector type in search index) |
| `wildcard` | Wildcard pattern matching on string fields |

---

### Count Results

Use the `count` option in `$searchMeta` to count matching documents without fetching them. Also works in `$search` via the `$SEARCH_META` aggregation variable when you need both results and count.

```javascript
// Count only (recommended)
db.movies.aggregate([
  {
    $searchMeta: {
      range: { path: "year", gte: 2010, lte: 2015 },
      count: { type: "lowerBound" }  // or "total" for exact count
    }
  }
])
// Returns: { count: { lowerBound: NumberLong(1001) } }
```

```javascript
// Count alongside results using $SEARCH_META
db.movies.aggregate([
  {
    $search: {
      text: { path: "title", query: "<query>" },
      count: { type: "total" }
    }
  },
  { $project: { title: 1, meta: "$SEARCH_META" } },
  { $limit: 10 }
])
```

| type | Behavior |
|---|---|
| `lowerBound` | Approximate. Exact up to `threshold` (default 1000), rough above it. |
| `total` | Exact count. Slower on large result sets. |

**Note:** Count affects performance — use only when needed (e.g., first page of paginated results).

---

### Pagination with searchSequenceToken

Cursor-based pagination using tokens. More efficient than `$skip` alone for deep pagination.

**Step 1 — Get tokens from the initial query:**
```javascript
db.movies.aggregate([
  {
    $search: {
      index: "<index-name>",
      text: { path: "title", query: "summer" },
      sort: { released: 1, _id: 1 }  // Sort on a unique field to prevent tie-ordering issues
    }
  },
  { $limit: 10 },
  {
    $project: {
      title: 1, released: 1,
      paginationToken: { $meta: "searchSequenceToken" }
    }
  }
])
```

**Step 2 — Next page using searchAfter:**
```javascript
db.movies.aggregate([
  {
    $search: {
      index: "<index-name>",
      text: { path: "title", query: "summer" },
      searchAfter: "<token-from-last-document-on-previous-page>",
      sort: { released: 1, _id: 1 }  // maintain the same sort order
    }
  },
  { $limit: 10 },
  { $project: { title: 1, paginationToken: { $meta: "searchSequenceToken" } } }
])
```

Use `searchBefore` with the first document's token on the current page to go to the previous page — results are returned in reverse order. Combine `searchAfter` with `$skip` to jump pages.

**Key constraint:** Query semantics (operator, path, query value, sort) must be identical between the initial query and any `searchAfter`/`searchBefore` query.

---

### Retrieve Arrays of Objects with returnScope

Return each element of an embedded document array as an individually scored document. Works in both `$search` and `$searchMeta`.

**Requirements:**
- Array field indexed as `embeddedDocuments` type with `storedSource` defined on the fields to return
- `returnStoredSource: true` in the query
- All operator paths must be nested under `returnScope.path` (use `hasAncestor` or `hasRoot` to query outside it)

**Index:**
```javascript
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "funding_rounds": {
        "type": "embeddedDocuments",
        "dynamic": true,
        "storedSource": {
          "include": ["round_code", "raised_currency_code", "raised_amount"]
        }
      }
    }
  }
}
```

**Query:**
```javascript
db.companies.aggregate([
  {
    $search: {
      range: { path: "funding_rounds.raised_amount", gte: 5000000, lte: 10000000 },
      returnStoredSource: true,
      returnScope: { path: "funding_rounds" }
    }
  },
  { $limit: 5 }
])
```

Only fields defined in `storedSource` within the embedded document are returned — root-level fields are excluded. When `returnScope` is specified, all query paths must start with `returnScope.path`.

---

### Advanced Query Syntax (queryString)

**Use case:** Complex search with boolean operators, wildcards, and field-specific queries.

**Fields configuration:**
```javascript
// Add to mappings.fields in your index:
{
  "title": { "type": "string" },
  "director": { "type": "string" },
  "year": { "type": "number" }
}
```

**Query patterns:**
```javascript
// Boolean operators
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      queryString: {
        defaultPath: "title",
        query: "detective AND (noir OR thriller) NOT comedy"
      }
    }
  }
])

// Field-specific searches
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      queryString: {
        defaultPath: "title",
        query: "title:inception AND director:nolan"
      }
    }
  }
])

// Wildcards and ranges
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      queryString: {
        defaultPath: "title",
        query: "star* AND year:[2010 TO 2020]"
      }
    }
  }
])
```

**Supported syntax:**
- Boolean: `AND`, `OR`, `NOT`
- Grouping: `(term1 OR term2)`
- Wildcards: `*` (0+ chars), `?` (single char)
- Ranges: `[min TO max]` for numbers/dates
- Field-specific: `fieldName:value`

**Key considerations:**
- Great for building search UIs with advanced options
- Users can construct complex queries without API changes
- Validate/sanitize user input to prevent injection

---

### Searching Nested Arrays (embeddedDocument)

**Use case:** Search within arrays of objects where element-wise comparisons are required (similar to $elemMatch), or each element must be scored independently.

**Fields configuration:**
```javascript
// Add to mappings.fields in your index:
{
  "title": { "type": "string" },
  "reviews": {
    "type": "embeddedDocuments",  // Required for array search
    "fields": {
      "author": { "type": "string" },
      "text": { "type": "string" },
      "rating": { "type": "number" }
    }
  }
}
```

**Query pattern:**
```javascript
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      embeddedDocument: {
        path: "reviews",
        operator: {
          compound: {
            must: [
              { text: { query: "excellent", path: "reviews.text" } }
            ],
            filter: [
              { range: { path: "reviews.rating", gte: 4 } }
            ]
          }
        },
        score: { embedded: { aggregate: "maximum" } }  // or sum, minimum, mean
      }
    }
  }
])
```

**Score aggregation options:**
- `sum`: Add scores from all matching array elements
- `maximum`: Use highest score from array elements
- `minimum`: Use lowest score from array elements
- `mean`: Average scores from array elements

**Key considerations:**
- Each array element is indexed as a separate document
- Use `embeddedDocuments` field type, not regular `document`
- Score aggregation controls how array matches affect overall document score
- Performance can be degraded due to complexity of parent-child joins

---

### Search Highlighting

**Use case:** Show users which parts of documents matched their query.

**Fields configuration:**
```javascript
// Add to mappings.fields in your index:
{
  "title": { "type": "string" },
  "plot": { "type": "string" }
}
```

**Query pattern:**
```javascript
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      text: {
        query: "detective noir",
        path: "plot"
      },
      highlight: {
        path: "plot",
        maxCharsToExamine: 500000,  // Default
        maxNumPassages: 5            // Number of snippets
      }
    }
  },
  {
    $project: {
      title: 1,
      plot: 1,
      highlights: { $meta: "searchHighlights" },
      score: { $meta: "searchScore" }
    }
  }
])
```

**Highlight result structure:**
```javascript
{
  "highlights": [
    {
      "path": "plot",
      "texts": [
        { "value": "A ", "type": "text" },
        { "value": "detective", "type": "hit" },
        { "value": " investigates a murder in ", "type": "text" },
        { "value": "noir", "type": "hit" },
        { "value": " Los Angeles", "type": "text" }
      ],
      "score": 1.23
    }
  ]
}
```

**Key considerations:**
- `type: "hit"` indicates matched terms
- `type: "text"` is surrounding context
- Multiple passages returned for long documents
- Use in search results UI to show match context

---

### Compound Queries

**Compound queries** combine multiple operators efficiently:

```javascript
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      compound: {
        must: [
          { text: { query: "detective", path: "plot" } }  // Required, affects score
        ],
        should: [
          { text: { query: "mystery", path: "genre" } }   // Optional, boosts score
        ],
        filter: [
          { range: { path: "year", gte: 2000 } }          // Required, no score impact
        ],
        mustNot: [
          { text: { query: "comedy", path: "genre" } }    // Excludes results
        ]
      }
    }
  }
])
```

**Clause types:**
- `must`: Required matches that affect scoring
- `should`: Optional matches that boost scores
- `filter`: Required matches that don't affect scoring (faster)
- `mustNot`: Exclusions

**Performance tips:**
- Use `filter` instead of `must` for criteria that shouldn't affect scoring (faster)
- Put most selective criteria in `must` or `filter` first
- Limit `should` clauses to 3-5 for best performance

---

### Query with Synonyms

When your index is configured with synonyms, specify the synonym mapping name in your query:

```javascript
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      text: {
        query: "car chase",
        path: "description",
        synonyms: "synonym-mapping-name"  // Reference the mapping from your index
      }
    }
  }
])
```

**Note:** When you specify a synonym mapping name, MongoDB Search automatically searches for the query terms AND all their synonyms (e.g., "car" also matches "automobile", "vehicle").

---

### Using Multi Analyzers

Query specific analyzer variants of a field:

```javascript
// Standard fuzzy search
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      text: {
        query: "Action",
        path: "title"  // Uses default analyzer
      }
    }
  }
])

// Exact match using keyword analyzer
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      text: {
        query: "Action",
        path: "title.keywordAnalyzer"  // Uses alternate analyzer
      }
    }
  }
])
```

**Use case:** Support both fuzzy and exact matching on the same field without duplicating data.

---

### Autocomplete

Search-as-you-type on fields indexed as `autocomplete` type (see lexical-search-indexing.md).

| Option | Description |
|---|---|
| `query` | String to search |
| `path` | Field indexed as `autocomplete` |
| `tokenOrder` | `any` (tokens in any order; sequential matches score higher) or `sequential` (tokens must be adjacent) |
| `fuzzy` | `{ maxEdits: 1\|2, prefixLength: <n>, maxExpansions: <n> }` |

To score exact matches higher, index the field as both `autocomplete` and `string` types and query using `compound`.

---

### Facet

Groups results into buckets by field values or ranges. Use with `$searchMeta` for metadata only, or with `$search` + `$SEARCH_META` variable for results and metadata.

```javascript
{ "$searchMeta": { "facet": {
    "operator": { <operator> },
    "facets": {
      "<facet-name>": { "type": "string|number|date", "path": "<field>", ...options }
    }
} } }
```

| Facet type | Field index type | Bucket definition |
|---|---|---|
| `string` | `token` | Top N unique string values. `numBuckets` defaults to 10. |
| `number` | `number` | Numeric ranges via `boundaries` array + optional `default` bucket |
| `date` | `date` | Date ranges via `boundaries` array + optional `default` bucket |

---

### geoShape

Query shapes by spatial relation. Field must be indexed as `geo` type with `indexShapes: true`. Required fields: `geometry` (GeoJSON Polygon, MultiPolygon, or LineString), `path`, and `relation`:

| relation | Meaning |
|---|---|
| `contains` | Indexed geometry contains the query geometry |
| `disjoint` | No overlap between geometries |
| `intersects` | Geometries overlap |
| `within` | Indexed geometry is within the query geometry (not supported for LineString or Point) |

---

### geoWithin

Query geographic points within a region. Field must be indexed as `geo` type. Specify one of:
- `box`: `{ bottomLeft: <GeoJSON Point>, topRight: <GeoJSON Point> }`
- `circle`: `{ center: <GeoJSON Point>, radius: <meters> }`
- `geometry`: GeoJSON Polygon or MultiPolygon

**For both geo operators:** longitude must be specified before latitude; longitude range [-180, 180], latitude range [-90, 90].

---

## Query Optimization

### Sorting Search Results

Use the `sort` option inside `$search` to sort at the mongot level (more efficient than a `$sort` stage after). Supports: `boolean`, `date`, `number`, `objectId`, `uuid`, and `string` (must be indexed as `token` type). Cannot sort on `embeddedDocuments` type fields.

```javascript
db.collection.aggregate([
  {
    $search: {
      text: { ... },
      sort: { "fieldName": -1, "title": 1, score: { $meta: "searchScore" } }
    }
  },
  { $limit: 10 }
])
```

**Sort by score:**
```javascript
sort: { score: { $meta: "searchScore", order: 1 } }  // ascending (lowest score first)
sort: { score: { $meta: "searchScore" } }             // descending (default)
```

**Null/missing values:** Appear first in ascending sort by default. Use `noData: "highest"` to push them last:
```javascript
sort: { "field": { order: 1, noData: "highest" } }
```

**Key rules:**
- `sort` inside `$search` only works on indexed fields — use `$sort` after for non-indexed or computed fields
- For `searchSequenceToken` pagination, sort must include a unique field (e.g., `_id`) to avoid tie-ordering
- Arrays: ascending uses smallest element, descending uses largest

### Using Stored Source

Retrieve frequently accessed fields directly from the search index instead of the database:

```javascript
db.collection.aggregate([
  {
    $search: {
      index: "search_index",
      text: { query: "detective", path: "plot" },
      returnStoredSource: true  // Retrieve from mongot, not DB
    }
  },
  { $limit: 20 },
  { $match: { rating: { $gte: 7 } } }  // Filter on stored fields
])
```

**Requirements:**
- Fields must be configured in `storedSource` in your index definition
- Dramatically improves performance by avoiding database lookups
- Especially beneficial when filtering or sorting after $search

---

### $match After $search

Minimize blocking stages after `$search` — prefer encapsulating filter logic inside the `$search` stage itself using `compound.filter`. This avoids additional mongod operations and makes full use of the Atlas Search index.

**Prefer `compound.filter` over `$match`** for fields indexed in the search index (string, token, number, date, boolean, objectId, uuid, geo):

```javascript
// Prefer this
{ $search: { compound: { must: [{ text: { ... } }], filter: [{ range: { path: "year", gte: 2000 } }] } } }

// Avoid this where possible
{ $search: { text: { ... } } },
{ $match: { year: { $gte: 2000 } } }
```

**If you must use `$match`** (e.g., for non-indexed or computed fields), use `storedSource` + `returnStoredSource` to avoid a full document lookup in mongod:

```javascript
{ $search: { text: { ... }, returnStoredSource: true } },
{ $match: { storedField: { $exists: true } } }
```

---

## Query Performance Analysis

Use `explain` to analyze query performance:

```javascript
db.collection.explain("executionStats").aggregate([
  { $search: { /* ... */ } }
])
```

**Important:** Atlas Search explain output differs from standard MongoDB explain. It shows execution on the search engine (mongot) side with Lucene-specific statistics, not standard MongoDB execution plans.
quick-start.md 44.9 KB
# Quick Start

**Scope**: This guide is a step-by-step walkthrough that demonstrates semantic search (using Automated Embedding), keyword search (using MongoDB Search), and hybrid search against the `sample_mflix` sample dataset in the user's cluster. It prescribes an exact interaction sequence, index names, and queries. For the underlying reference material behind each step, see `automated-embedding.md`, `vector-search.md`, `lexical-search-indexing.md`, `lexical-search-querying.md`, and `hybrid-search.md`.

**Only run this once the user has chosen the sample-data tour.** It teaches how search works on a fixed dataset; it does not build search for the user's own collections. If you arrived here from a general request like "I'm new to search, help me get started" without the user picking the tour over working on their own data, go back to `SKILL.md` Step 0 and offer that choice first.

**This walkthrough requires an Atlas cloud cluster.** The sample dataset loads from the Atlas UI, and Automated Embedding works on every Atlas tier with no key management. Atlas Local and self-managed MongoDB are out of scope — Step 0.2 covers how they get detected and routed out.

## Interaction Principle

**Act first. Explain second. Then ask.**

Every step follows the same rhythm:
1. Do something automatically (create an index, run a query)
2. Explain what just happened in plain language
3. Ask if the user wants to go one step further

Never ask the user to decide something they haven't seen yet.

**Never end a turn without the next step.** Every turn closes with an AskUserQuestion or a completed action, and a step's question goes in the same turn as its explanation. The only valid stopping points are the user choosing to stop, or Wrap Up.

**"No" does not end the walkthrough, except at a bridge step.**

- **Enrichment questions** (6a, 7a, 5b, 6b, 9c) offer an optional extra inside the current path. A decline advances to that path's bridge step: 8a for Path A, 6a2 for Path A2, 7b for Path B, Wrap Up for Path C.
- **Bridge questions** offer the next search mode. A decline goes to Wrap Up, the only place an intermediate "No" ends the tour.

Never re-offer a declined branch, and never substitute one the user didn't ask for.

## Creating an Index

Four steps create one: Step 4a (`quickstart_semantic`), Step 4a2 (`quickstart_manual`), Step 3b (`quickstart_text`), and Step 6b (`quickstart_autocomplete`). Both rules below apply at every one of them.

**1 — Ask first.** `create-index` mutates the cluster, so it needs the explicit approval `SKILL.md` requires, in the turn immediately before the call. Steps 4a, 3b, and 6b each carry their own confirmation question; Step 4a2 is reached only by the user picking **Try with existing embeddings** or **Switch to manual embeddings**, which is itself the approval. Never treat a path choice as index approval: picking Hybrid at Step 2, or answering yes at Step 8a or Step 7b, selects a route, not consent to each index along it.

**2 — Check the name before using it.** Run `collection-indexes` on the target collection first, because re-running the tour on a cluster that already has these index names is the common case.

- **Name free** → create it.
- **Name taken, definition matches what the step would create** → create nothing. Tell the user you're reusing it and skip to that step's query if the status is `READY`. `Building` or `Pending` → poll per Step 3a.3 ②. `Stale` → handle per Step 3a.3 ②.
- **Name taken by a different definition** → do **not** drop it. Say the name is in use and create `<name>_2` instead. That name then replaces the original everywhere downstream: the step's own queries, Path C's pipelines, and the matching `SEMANTIC_INDEX_NAME`, `TEXT_INDEX_NAME`, or `AUTOCOMPLETE_INDEX_NAME` constant if the Wrap Up script is handed over. Carry any collision name you created to Wrap Up; left at its default, the script stops on the conflicting index instead of reusing yours.

## Step 0 — Check Connection and Deployment

**0.1 — Verify the MongoDB MCP is connected** by calling `list-databases`.

- If it **succeeds**: continue to 0.2.
- If it **fails**: get the connection working before continuing. If the `mongodb-mcp-setup` skill is available, invoke it inline. If it is not available (it does not ship in every plugin), tell the user:
  > "I can't reach your cluster through the MongoDB MCP server. Check that the server is running and that `MDB_MCP_CONNECTION_STRING` (or your Atlas service account credentials) is set in your client config, then restart the client and tell me when it's ready."

  Do not continue until `list-databases` succeeds.

**0.2 — Determine the deployment without asking (silent).** Do **not** ask the user what kind of deployment they have.

**Principle, used again in Step 3a: never block a beginner on a question they can't answer. Try the real operation and let its result tell you what the deployment supports.**

- **Opportunistic confirmation only.** If `atlas-local-list-deployments` exists *and* reports a running deployment you are connected to, that is positive evidence of **Atlas Local**: route out with the message below. Neither tool's absence or failure proves anything, because `atlas-local-list-deployments` ships only with the local MCP server and `atlas-inspect-cluster` is unregistered whenever the server has a connection string but no Atlas API service account.
- **Otherwise default to Atlas cloud** and proceed silently to Step 1. That is the overwhelmingly common case and the one this walkthrough is written for. Attempt no other probe: the MongoDB MCP server exposes no tool that returns cluster hostnames or raw command output.

**Where non-Atlas deployments actually get caught:** Step 1 cannot find or load `sample_mflix`, or Step 4a's `autoEmbed` index build fails. Both are real evidence; use the routing message below at that point.

**If there is real evidence of Atlas Local or self-managed MongoDB:** stop the walkthrough. Do not suggest starting a local deployment — they are already running MongoDB somewhere. Tell the user:
> "This guided walkthrough is only available for a cluster with the sample movies dataset on Atlas. Two options:
>
> 1. **Connect to a free Atlas cluster** (M0, no card required), load the sample dataset, and we'll run this tour end to end.
> 2. **Skip the tour and build search on your own data here.** Tell me what you want to search and I'll design the index and queries against your actual collections."

Use AskUserQuestion with those two options. If the user picks 1, wait for the Atlas cloud connection and restart at Step 0. If they pick 2, leave this walkthrough and use the main skill workflow in `SKILL.md`; without Voyage AI keys configured, semantic search there means manual embeddings (`vector-search.md`), not `autoEmbed`.

**0.3 — Confirm index creation is available.** Every path here creates at least one search index, so check for a `create-index` tool before starting one. If it is absent, the session is read-only in the sense `SKILL.md` defines (no `create`, `update`, or `delete` operation tools) and the walkthrough cannot complete. Do not enter a path and stop at its creation step. Tell the user:
> "I can read your cluster in this session but not create search indexes, so I can't run the guided tour for you. What I can do is design the indexes and queries and hand you the index JSON to create in the Atlas UI yourself."

Then leave this walkthrough and use the main skill workflow in `SKILL.md`, which handles read-only mode.

## Step 1 — Load Sample Data

Use `list-databases` to check if `sample_mflix` exists on the cluster.

**If it does not exist:** tell the user:
> "We'll use a sample movies dataset that Atlas provides. To load it: go to cloud.mongodb.com → your cluster → click the vertical ellipses → select **Load Sample Dataset**. Come back once it's loaded."

Wait for confirmation, then re-run `list-databases` to verify `sample_mflix` now appears. If it does not appear yet, tell the user:
> "It's not available yet. Give it another moment and let me know when it's loaded."

Repeat until `sample_mflix` is confirmed present before continuing.

**If the user reports there is no Load Sample Dataset option**, that is the real evidence Step 0.2 was waiting for: the deployment is not Atlas cloud. Stop here and use the routing message in Step 0.2. Do not ask which kind of non-Atlas deployment it is — the routing message is the same either way.

**For everyone (whether dataset was just loaded or already present):**

**Confirm the collection, not just the database name.** A cluster can carry a `sample_mflix` database that is not the Atlas sample dataset, so run `list-collections` on it before anything else. Only `movies` matters here; `embedded_movies` is checked at Step 3a2, and its absence does not block Path A, B, or C.

- **`movies` missing:** the sample dataset is not loaded, whatever the database name suggests. Repeat the Load Sample Dataset instructions above and re-verify, treating "there is no Load Sample Dataset option" exactly as described above — the Step 0.2 routing message.
- **`movies` present but `collection-schema` shows no `title`, `plot`, or `genres`:** this is the user's own collection, not the sample one. Do not index it and do not rename anything. Use the Step 0.2 routing message; its second option, building search on their own data through `SKILL.md`, is the fit here.

Otherwise use `collection-schema` on `sample_mflix.movies`, show a condensed example document (`title`, `plot`, `genres` only), and tell the user this is a real dataset of ~21,000 movies already on their cluster, one document per movie, with `title`, `plot`, and `genres` being the fields the walkthrough makes searchable — the same structure they would use for their own content.

## Step 2 — Choose Your Path

**Skip this step if the user already named a search type** when they asked ("I want to try vector search", "show me keyword search") — go straight to Path A, Path B, or, for hybrid, the hybrid route below. Do not re-ask a question they already answered. Skip only this question: Step 0's connection check and Step 1's `sample_mflix` check still have to pass before any path starts.

Otherwise use AskUserQuestion to ask:

> "What kind of search do you want to try?"

- **Semantic Search** *(Recommended)* — Find results by meaning, even when words don't match. Best for discovery, recommendations, and natural language queries.
- **Keyword Search** — Find results by exact words, with typo tolerance and autocomplete. Best for search boxes where users type specific terms.
- **Hybrid Search** — Run both at once and merge the rankings. Best when queries mix exact terms with open-ended intent.
- **I'm not sure** — routes to Semantic Search with an extra line of explanation.

**If the user picks Hybrid, or asked for hybrid by name:** hybrid needs a semantic index *and* a keyword index on `sample_mflix.movies`, so create both before Path C, in this order, confirming each.

1. Say so before creating anything:
   > "Hybrid search runs keyword and semantic search together, so it needs both kinds of index on the movies collection. I'll build the semantic one first, then the keyword one, and I'll check with you before each. Then we'll run the hybrid query."
2. **Semantic index.** Run Step 3a and Step 4a in full, Step 4a's AskUserQuestion confirmation included. Skip Steps 5a through 8a.
3. **Keyword index.** Run Step 3b only. Skip Steps 4b through 7b.
4. Go to Path C.

If at Step 4a the user takes **Try with existing embeddings** instead, hybrid on `movies` is off the table, because Path A2 builds on `embedded_movies`. Run Path A2 from Step 3a2 and let Step 6a2's disclosure offer the second index.

## Path A: Semantic Search (Automated Embedding)

### Step 3a — Cluster Readiness

Apply the Step 0.2 principle to cluster tier: try the real operation and let its result tell you what the tier supports. Do NOT ask the user "what tier are you on?" up front.

**3a.1 — Try to auto-detect the tier (silent, best-effort).**

Attempt `atlas-inspect-cluster`. It returns cluster metadata, of which two fields matter here:

- `instanceType`, one of `FREE`, `FLEX`, or `DEDICATED`
- `instanceSize`, populated only when `instanceType` is `DEDICATED` (`M10`, `M20`, and so on)

`instanceType` is what drives the index caps in 3a.3 ①.

**Storage auto-scaling is not readable.** No MCP tool returns it. Never gate on it, and never claim to have checked it. On `DEDICATED`, treat it as unknown, continue to the build, and rely on the `Stale` signal in 3a.3 ② as the only evidence that disk ran out.

- **If it succeeds:** note `instanceType` internally and apply the tier-specific guidance in 3a.3. Don't make the user do anything.
- **If it fails** (401 Unauthorized / no Atlas Admin API key / any error): do NOT stop and do NOT interrogate the user. Ask and continue:
  > "I couldn't automatically read your cluster tier — that needs a separate Atlas management key, which isn't required for anything we're doing. No problem: I'll just build the index, and if your tier can't support it, the build itself will tell us and I'll walk you through the fix."

  (Optional, offered as help — never required:)
  > "If you're curious, your tier is shown right under your cluster's name in the Atlas UI — e.g. 'M0 Sandbox', 'Flex', or 'M10'."

**3a.2 — Proceed straight to the index build (the real test).** Go to Step 4a, which walks through the cost and creates the `quickstart_semantic` auto-embed index. The creation call is the source of truth — it either succeeds or returns one of the two catchable errors in 3a.3.

**3a.3 — Catch the only two real failures.**

**① Index-count cap (Free/Flex).** Current limits: **M0 = 3** search/vector indexes total, **Flex = 10** total — and these counts include indexes already on the collection. If `create-index` returns an error about exceeding the maximum number of indexes:
  > "Heads up — you've hit your cluster's index limit. Free (M0) clusters allow **3 search/vector indexes total** and Flex allows **10**. These counts include any indexes already on the cluster.
  >
  > Two ways forward:
  > - **Make room:** delete an unused search index, or
  > - **Scale up:** move to Flex (10) or a dedicated tier for more headroom.
  >
  > Want me to list your existing indexes so we can see what's using the budget?"

  If they agree, run `collection-indexes` and show the current indexes so they can choose which ones to remove. Never delete anything without explicit confirmation. After freeing room or scaling, retry the build.

**② Dedicated cluster without storage auto-scaling (auto-embed only).** Automated Embedding on dedicated (`M10+`) clusters **requires storage auto-scaling**. This is a *disk* requirement, not a compute/tier one: do **not** tell users to raise their max cluster tier.

  The failure mode is **not** a failed build. Out of disk, MongoDB *pauses* embedding generation and the index goes **`Stale`**, resuming on its own once disk is freed. A `Stale` status from `collection-indexes` is the only signal; `create-index` never errors.

  **Polling procedure.** Once `create-index` returns, poll `collection-indexes` on `sample_mflix.movies` roughly every 30 seconds, reporting progress instead of going quiet:

  1. `READY` → continue to the next step in the current path.
  2. `Building` or `Pending` → keep polling. Expect 2 to 5 minutes for ~21,000 movies. Past 10 minutes with no change, say so and keep polling.
  3. `Stale` → stop polling and show the message below. Never drop or re-create the index, because the embeddings generated so far are kept.

  On `Stale`:
  > "Automated Embedding on a dedicated cluster **requires storage auto-scaling**. MongoDB stores the generated embeddings on your own cluster, so the index needs room to grow as it embeds your documents. Your cluster ran out of disk, so embedding generation paused and the index went into a `Stale` state. Nothing is lost, and it resumes on its own once there's space again.
  >
  > To enable it: Atlas UI → your cluster → **Edit Configuration** → **Storage** → turn on **storage auto-scaling**, then tell me when it's on.
  >
  > Prefer not to change cluster settings? We can switch to the manual-embeddings path instead. It uses pre-computed vectors already in the sample data, with no embedding generation and no token usage."

  Then use AskUserQuestion with exactly these two options:

  - **I enabled storage auto-scaling** → resume polling the *same* index from step 1 above. Do not call `create-index` again, and do not repeat Step 4a's explanation or confirmation.
  - **Switch to manual embeddings** → go to Path A2.

  Do not poll while waiting for that answer, and do not wait for the status to clear by itself. Nothing changes until the user acts.

  **Note on tiers:** this requirement is scoped to dedicated clusters and does **not** mean autoEmbed requires `M10+`. Free and Flex can use Automated Embedding, subject to ①'s caps and Free Tier rate limits. Never tell a Free/Flex user it is unavailable to them.

### Step 4a — Recommend AutoEmbed Index

**Cost is an FYI, not a gate.** The token note below is part of explaining how Automated Embedding works. Never turn it into a separate decision the user has to settle first, and never ask them to approve spend before they have seen what the feature does.

Before creating anything, explain the value and cost:

> **Here's how Automated Embedding works:**
>
> MongoDB handles everything — you don't write any embedding code. When you create this index, MongoDB reads every movie plot and converts it into a **vector** (a list of numbers that captures its meaning) using a Voyage AI model called **voyage-4**. It does this automatically, in the background, every time you add or update a document.
>
> **Token allocation:**
> - You get **200 million free tokens** per model, per organization — one-time, shared across all your Atlas projects
> - After that, voyage-4 costs **$0.06 per million tokens**
> - For reference: ~21,000 movie plots is roughly 5–10M tokens total for the initial sync
>
> **If you're on M0:** Once your 200M free tokens are exhausted, MongoDB automatically invoices you for additional usage — index builds and queries don't stop. You can add a payment method to your Atlas account without upgrading your cluster (Atlas → Billing → Payment Method). Charges are only for embedding model usage.
>
> **Two more things worth knowing before you commit:**
> - **Where the embedding happens.** The embedding model runs on inference infrastructure that MongoDB operates — a multi-tenant service on Google Cloud in a **US region** — *regardless of which cloud provider or region your cluster is in*. Your text is sent there to be embedded. **Data transfer costs apply** on top of the token costs above. If you have data-residency requirements, this is the detail to check first.
> - **Where the embeddings are stored.** They live on *your* cluster, in a dedicated internal database (one generated-embeddings collection per autoEmbed index). So they consume your disk, which is why dedicated clusters need storage auto-scaling.
>
> **The index we'd create looks like this:**
> ```json
> {
>   "fields": [
>     { "type": "autoEmbed", "modality": "text", "path": "plot", "model": "voyage-4" },
>     { "type": "filter", "path": "genres" }
>   ]
> }
> ```

Use AskUserQuestion:
> "Want to create this index and try semantic search?"

- **Yes, create it** → proceed to create the index
- **Try with existing embeddings** → route to Path A2 (manual vector search using pre-embedded data, no auto embedding needed)

If yes, apply the name check in **Creating an Index** rule 2 to `sample_mflix.movies`, then use `create-index` (or `mcp__mongodb-mcp-server__create-index`) to create a Vector Search index with `autoEmbed` type on it using the definition above.

Name the index: `quickstart_semantic`, or the collision name rule 2 produced. If rule 2 found a matching `READY` index, create nothing and go straight to Step 5a — skip the build message below.

**While the index builds, tell the user:**
> "MongoDB is now generating embeddings for all ~21,000 movie plots. This runs in the background and typically takes a few minutes for a collection of this size. I'll check when it's ready."

Wait for status `READY` with `collection-indexes` before running any queries, following the polling procedure in Step 3a.3 ②.

### Step 5a — First Semantic Query

Tell the user:
> "Let's run your first semantic query: **'a story about growing up'**"

Run this aggregation with `aggregate`:

```javascript
db.movies.aggregate([
  {
    $vectorSearch: {
      index: "quickstart_semantic",
      path: "plot",
      query: "a story about growing up",
      numCandidates: 100,
      limit: 3
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

Display results in a clean table: Title | Score | Plot (truncated to ~100 chars).

**Explain to the user:**
> "None of those movie titles or plots contain the words 'growing up', but MongoDB found them anyway. That's semantic search: it matched the **meaning** of your query, not the words. The score shows how similar each result is to what you asked for: closer to 1.0 means more similar."

Point out one detail of the query you just ran: `query` is a plain text string, not a vector. With auto embedding MongoDB converts it internally, so the application never generates query vectors.

### Step 6a — Explore Another Query

Use AskUserQuestion:
> "Want to try another query to see it work on a different theme?"

- **"unlikely friendship"** → run and show results
- **"revenge and justice"** → run and show results
- **Type your own** → run whatever they enter
- **Skip, move on** → proceed to Step 7a

After results: point out which movies surfaced and note whether any of the query words appear in the plot. If they don't — highlight it.

### Step 7a — Try Filtering

Use AskUserQuestion:
> "Want to narrow the results to a specific genre? Filters let you combine semantic similarity with exact criteria like 'find me something emotionally similar to this query, but only in the Drama genre.'"

- **Yes, show me filtered search** → proceed
- **No, move on** → skip to Step 8a

If yes, run the same query with a genre filter:

```javascript
db.movies.aggregate([
  {
    $vectorSearch: {
      index: "quickstart_semantic",
      path: "plot",
      query: "a story about growing up",
      filter: { genres: { $eq: "Drama" } },
      numCandidates: 150,
      limit: 3
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      genres: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

**Explain:**
> "MongoDB applied the genre filter **before** computing similarity. This narrows the candidate pool first, then finds the most semantically similar ones within it. This is faster than filtering after the fact."

Note that `filter` takes standard MongoDB query syntax and works on any field indexed as `type: filter`. Raising `numCandidates` (150 here versus 100 unfiltered) compensates for the narrowed pool.

### Step 8a — Bridge to Keyword / Hybrid

Use AskUserQuestion:
> "Semantic search is great for open-ended queries. Keyword search is better when users type specific titles or names. Want to see them side by side, then combine them into hybrid search?"

- **Yes** → run the abbreviated Path B below, then go to Path C
- **No, I'm done** → skip to Wrap Up

**Abbreviated Path B, reached only from here.** Run Steps 3b, 4b, and 5b, then go straight to Path C. **Skip Step 6b** (autocomplete is a detour from the comparison the user just asked for; offer it in Wrap Up only if they raise it) and **skip Step 7b's question** (they answered it here).

## Path A2: Semantic Search (Bring Your Own Embeddings)

*This path is for users who prefer not to use Automated Embedding. Uses the `sample_mflix.embedded_movies` collection, which already has pre-computed 1536-dimensional plot embeddings from OpenAI's text-embedding-ada-002 model.*

**Path A2 replaces Path A. It is not a continuation of it.** Two entry points lead here: Step 4a's **Try with existing embeddings** option, before any autoEmbed index exists, and Step 3a.3 ②'s **Switch to manual embeddings** option, after one went `Stale`. Either way, Path A's remaining steps are skipped and `quickstart_semantic` does not exist on `sample_mflix.movies`. Returning to Path A later means running Step 4a in full, explanation and AskUserQuestion confirmation included, because it builds a different index on a different collection. There is no shortened return route.

### Step 3a2 — Explain Manual Vector Search

Tell the user the sample dataset already includes an `embedded_movies` collection with pre-computed vectors on every document, so no embedding API is needed. With manual vector search the application generates embeddings with a model of its choice (OpenAI, Cohere, Hugging Face) and stores them as a document field; MongoDB only does the similarity search. Show the document shape:

```json
{
  "title": "Toy Story",
  "plot": "A cowboy doll is profoundly threatened...",
  "plot_embedding": [0.0007, -0.0268, 0.0135, ...]  // 1536 numbers
}
```

Because the vectors are supplied rather than generated, the index definition must declare the dimension count and similarity metric itself — both are shown in Step 4a2 and must match the model that produced the vectors.

### Step 4a2 — Create Manual Vector Index

Apply the name check in **Creating an Index** rule 2 to `sample_mflix.embedded_movies`, then use `create-index` to create a vectorSearch index on it:

```json
{
  "fields": [
    {
      "type": "vector",
      "path": "plot_embedding",
      "numDimensions": 1536,
      "similarity": "cosine"
    }
  ]
}
```

Name the index: `quickstart_manual`, or the collision name rule 2 produced.

**While it builds, explain:**
> "The index organizes the embeddings that are already stored in your documents into a structure that makes similarity lookups fast."

Wait for status `READY` with `collection-indexes`.

### Step 5a2 — Run a "Find Similar Movies" Query

Explain to the user:

> "To query a manual vector search index, you need to pass a vector, which is an array of numbers representing the query terms. Normally your app generates this by sending the user's search text to an embedding model. Because we don't have an embedding API connected here, we take a movie we already know and find others with similar plots. This is exactly how recommendation systems work."

Use `find` on `sample_mflix.embedded_movies` to fetch the `plot_embedding` for **"Toy Story"**: filter `{"title": "Toy Story"}`, projection `{"plot_embedding": 1, "title": 1}`, limit 1. Use this movie rather than picking one, so the results below are reproducible. If it returns nothing, fall back to `{"title": "The Matrix"}`; if that also returns nothing, take the first document that has a `plot_embedding` field and tell the user which movie you used.

Then run:

```javascript
db.embedded_movies.aggregate([
  {
    $vectorSearch: {
      index: "quickstart_manual",
      path: "plot_embedding",
      queryVector: <the plot_embedding array fetched for "Toy Story" above>,
      numCandidates: 100,
      limit: 5
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

Display results in a table: Title | Score | Plot snippet. Exclude the source movie from the display.

**Explain:**
> "MongoDB compared the query vector against every stored embedding and returned the most similar ones. The top result is the source movie itself (score ~1.0), so skip that one. The rest are movies whose plots are mathematically closest in meaning. No keyword matching. Instead, it's pure similarity between vectors."

> **In your own app:** instead of using an existing document's embedding as the query, you'd call your embedding model with the user's search text and pass the result as `queryVector`. The query structure is identical.

### Step 6a2 — Bridge to Keyword / Hybrid

Use AskUserQuestion:
> "Do you want to also see keyword search and hybrid, where both approaches run together? One thing to flag first: keyword search runs on the `movies` collection, and hybrid needs a semantic index on that same collection. The one we just built is on `embedded_movies`, so hybrid would mean creating a second semantic index on `movies` with Automated Embedding. I'll ask before creating it."

- **Yes** → proceed to Path B, then Path C. Path C's Path A2 branch handles that second index, with its own confirmation.
- **No, I'm done** → skip to Wrap Up

## Path B: Keyword Search (Atlas Search)

### Step 3b — Create Text Search Index

Ask before creating anything, with AskUserQuestion:
> "Keyword search needs a MongoDB Search index on the movies collection — a separate structure MongoDB builds alongside your data, like the index at the back of a book. It doesn't change your documents, it just makes specific fields fast to search. Want me to create it?"

- **Yes, create it** → continue below
- **No** → Path B and Path C both need this index, so skip to Wrap Up and do not re-offer it

This question is required on every route in, including Step 2's hybrid route, Step 8a's abbreviated Path B, and Step 7b. Those answers chose a path; none of them approved this index.

Then apply the name check in **Creating an Index** rule 2 to `sample_mflix.movies` and use `create-index` to create an Atlas Search index on it:

```json
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": { "type": "string" },
      "plot": { "type": "string" },
      "genres": { "type": "token" }
    }
  }
}
```

Name the index: `quickstart_text`, or the collision name rule 2 produced — that name then goes in every `$search` stage below and in Path C's keyword pipeline.

**Explain while it builds:**
> "We're indexing title and plot as searchable text, plus genres as an exact-match field you can filter on. It builds in the background and your documents stay exactly as they are."

The queries in this path search `title` and `plot` only. `genres` is indexed as `token` so exact-match filtering is available, mirroring the `filter` field in Path A's vector index. Do not claim the queries below search `genres`.

### Step 4b — First Keyword Search

Run with `aggregate`:

```javascript
db.movies.aggregate([
  {
    $search: {
      index: "quickstart_text",
      text: {
        query: "space adventure",
        path: ["title", "plot"]
      }
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      score: { $meta: "searchScore" }
    }
  },
  { $limit: 3 }
])
```

Display results in a table: Title | Score | Plot snippet.

**Explain:**
> "MongoDB Search found movies where 'space' and 'adventure' appear across the title or plot, and ranked them by how relevant they are. The score reflects relevance, not just whether the word appeared."

Contrast it with `$vectorSearch`: `$search` takes a `text` operator and matches words, `$vectorSearch` takes `query` and matches meaning. `path` accepts an array, so one `text` operator covers several fields at once.

### Step 5b — Try Fuzzy Matching

Use AskUserQuestion:
> "Want to see what happens with a typo? Fuzzy matching is one of the most practical features for real search boxes."

If yes, run with intentional typos (`"sapce adventre"`):

```javascript
db.movies.aggregate([
  {
    $search: {
      index: "quickstart_text",
      text: {
        query: "sapce adventre",
        path: ["title", "plot"],
        fuzzy: { maxEdits: 1 }
      }
    }
  },
  {
    $project: { _id: 0, title: 1, score: { $meta: "searchScore" } }
  },
  { $limit: 3 }
])
```

**Explain:**
> "Both typos were tolerated. MongoDB allowed up to 1 character difference between the query and indexed text. This is what makes a search box feel forgiving and human."

`fuzzy: { maxEdits: 1 }` is the only addition to the previous query — one character of difference per word. `maxEdits: 2` is more forgiving but too loose in practice: short words start matching things they shouldn't.

### Step 6b — Try Autocomplete

Use AskUserQuestion:
> "Want to see search-as-you-type? This powers the dropdown suggestions that appear while someone is still typing."

Autocomplete needs `title` indexed as an `autocomplete` type, which `quickstart_text` does not have yet. Two routes get there. **Work through this in order, before telling the user anything:**

1. **Does an autocomplete index already exist?** Check the `collection-indexes` output. If `quickstart_autocomplete` is there with `title` typed as `autocomplete`, create nothing, tell the user you're reusing it, and go straight to the query. If that name is taken by a different definition, do **not** drop it: say the name is in use and create `quickstart_autocomplete_2` instead. That name then replaces `quickstart_autocomplete` in the Route 2 pipeline and in the Wrap Up script's `AUTOCOMPLETE_INDEX_NAME` constant.
2. **Can you execute mongosh or driver code in this session?** If yes, Route 1. If the MongoDB MCP server is your only path to the cluster, Route 2. Atlas UI access does not qualify, because it means handing the step to the user to do by hand, and this walkthrough never does that when a tool can do it.
3. **Did Route 1 fail?** If `updateSearchIndex` is missing or errors for any reason, fall back to Route 2 and say why. Never drop `quickstart_text` to work around it.

When unsure, take Route 2. It works in every setup and leaves the index already serving queries untouched.

**Route 1 — edit the existing index.** Requires mongosh or a driver. `db.collection.updateSearchIndex(<name>, {<definition>})` updates an index in place: the old definition keeps serving queries while the new one builds, then swaps over. Pass the **complete** new definition (it replaces, not merges), with `title` as a multi-type field:

```json
"title": [
  { "type": "string" },
  { "type": "autocomplete", "tokenization": "edgeGram" }
]
```

**⚠️ Route 2 — create a second index.** The default, and the only option when the MongoDB MCP server is your path to the cluster: it exposes `create-index` and `drop-index` but **no update-index tool**, so `quickstart_text` cannot be edited in place from here. Don't attempt it and don't drop the working index. Create a dedicated index named `quickstart_autocomplete`:

```json
{
  "mappings": {
    "dynamic": false,
    "fields": {
      "title": { "type": "autocomplete", "tokenization": "edgeGram" }
    }
  }
}
```

Then query it with `index: "quickstart_autocomplete"`, or the collision name from step 1, instead of `quickstart_text`. It counts against the tier index caps in Step 3a.3 ①. The Wrap Up script takes this second-index route too, so its `AUTOCOMPLETE_INDEX_NAME` constant is covered by the handoff rule in **Creating an Index** rule 2.

Tell the user which route you took and why, then run that route's query. **The index name is not interchangeable: using the wrong one returns an error, because only one of the two indexes has `title` typed as `autocomplete`.**

**Route 2 (second index):**
```javascript
db.movies.aggregate([
  {
    $search: {
      index: "quickstart_autocomplete",
      autocomplete: { query: "inc", path: "title" }
    }
  },
  {
    $project: { _id: 0, title: 1 }
  },
  { $limit: 5 }
])
```

**Route 1 (updated index):** same pipeline with `index: "quickstart_text"`.

**Explain:**
> "Three characters returned relevant title suggestions instantly. Autocomplete pre-indexes word fragments, so it's purpose-built for speed and can respond as fast as a user types."

Note the operator change: `autocomplete` replaces `text` inside `$search`, `query` holds the partial input, and `path` must point at a field indexed as `autocomplete` type — this is the call a search box makes on every keystroke.

### Step 7b — Bridge to Hybrid

Use AskUserQuestion:
> "Keyword search finds exact matches. Want to see hybrid search, where MongoDB runs both keyword and semantic search at once and merges the results into one ranked list?"

- **Yes** → proceed to Path C
- **No, just the script** → skip to Wrap Up

## Path C: Hybrid Search

*Prerequisites: the `quickstart_text` index (from Path B) and the `quickstart_semantic` index (from Path A), both on `sample_mflix.movies`.*

**How users get here.** Step 2's hybrid route, Step 8a (from Path A), or Step 7b (from Path B). All three have already created or confirmed the two indexes, and nothing below changes based on which one it was.

Run `collection-indexes` on `sample_mflix.movies` to confirm both exist. If either is missing, don't create it implicitly: re-enter only the step that creates it (Step 3b for `quickstart_text`, Step 4a for `quickstart_semantic`) as a **create-only re-entry**:

- Run that step's explanation and its confirmation question again. That is the user's consent to build an index, so it is never skipped or assumed.
- Run nothing else from that path: no repeating queries or explanations the user already saw, no re-offering branches they declined.
- Come back here, re-run `collection-indexes`, and continue to Step 8c once both report `READY`.

If the user arrived through Path A2, they have `quickstart_manual` on `sample_mflix.embedded_movies`, a different index on a different collection that this pipeline can't use. Tell the user:

> "Hybrid search needs both pipelines pointed at the same collection, so the semantic index has to be on `movies` alongside the keyword index. Yours is on `embedded_movies` from earlier. I can create an Automated Embedding index on `movies` instead. That generates embeddings for about 21,000 plots and counts against your tier's search index cap. Want me to?"

If the user agrees, run Step 4a as a create-only re-entry under the rules above, then continue. If they decline, skip to Wrap Up and do not ask again.

### Step 8c — Run Hybrid Search

Run with `aggregate`:

**Two things to flag to the user before running it — both look like mistakes and aren't:**

1. **The two pipelines search for different text on purpose.** Semantic gets `"a story about growing up"` (a natural-language description of a *theme*), keyword gets `"coming of age"` (the literal *phrase* a plot would actually contain). Each pipeline is fed the query form it's good at. Say this out loud, or a beginner could read it as a typo.
2. **`limit: 20` inside each pipeline is the merge window**, and it is load-bearing. It caps how many documents `$rankFusion` evaluates from each pipeline — so cross-pipeline agreement is only visible *inside* that window. Set it to 5 and a document ranked #7 by keyword becomes invisible to the fusion, even if it's the best overall result. A reasonable default is 3–5× the number of final results you want.

```javascript
db.movies.aggregate([
  {
    $rankFusion: {
      input: {
        pipelines: {
          semanticPipeline: [
            {
              $vectorSearch: {
                index: "quickstart_semantic",
                path: "plot",
                query: "a story about growing up",
                numCandidates: 100,
                limit: 20
              }
            }
          ],
          keywordPipeline: [
            {
              $search: {
                index: "quickstart_text",
                text: { query: "coming of age", path: "plot" }
              }
            },
            { $limit: 20 }
          ]
        }
      },
      combination: {
        weights: {
          semanticPipeline: 0.7,
          keywordPipeline: 0.3
        }
      }
    }
  },
  {
    $project: { _id: 0, title: 1, plot: 1 }
  },
  { $limit: 5 }
])
```

Display results.

**Explain:**
> "MongoDB ran two searches, one by meaning and one by keywords, then merged them using an algorithm called **Reciprocal Rank Fusion**. Movies that ranked highly in **both** searches scored highest overall. The weights (70% semantic, 30% keyword) control how much each signal matters. You can tune these per query type."

Two facts about the pipeline worth stating: the sub-pipelines run one after another rather than in parallel, with the ranked results merged at the end, and `$rankFusion` is not limited to two — any number of pipelines can be weighted to fit the use case.

### Step 9c — Try Different Weights (Optional)

Use AskUserQuestion:
> "Want to flip the weights and see how results change? For example, trust keywords more when users type exact titles."

If yes, re-run with `keywordPipeline: 0.7, semanticPipeline: 0.3` and show the diff in results.

**Explain:**
> "Different weights, different results. In a real product you might boost keyword search for navigational queries (user knows what they want) and boost semantic search for exploratory queries (user is browsing)."

## Wrap Up

Congratulate the user. Use AskUserQuestion:
> "Want a standalone Python script with everything you just ran: index creation, semantic search, keyword search, and hybrid search?"

**Check the index state before asking that.** Run `collection-indexes` on `sample_mflix.movies` and check for the semantic index name carried from Step 4a (for example, `quickstart_semantic` or `quickstart_semantic_2`). The script creates that named index there as its first action and embeds about 21,000 movie plots, which uses tokens.

- **The carried semantic index is present:** the script reproduces what the user already ran and agreed to. Ask the question above as written.
- **Absent:** the script would do embedding work the user never approved, so say so instead of asking the question above. Gate on this index, not on which path was taken: the gap covers Path A2 ending at Step 6a2, Path B ending at Step 7b, Path A stopping at Step 4a's confirmation, and any path cut short by an error.
  > "I have a standalone Python script covering all three search types, but it goes further than what you just ran: it creates an Automated Embedding index on `movies` and embeds about 21,000 movie plots, which uses tokens. Want it anyway?"

If they decline, do not copy the script. Otherwise copy `scripts/quickstart_complete.py` from this skill directory into the user's working directory.

**Then carry over any collision names.** The script's `SEMANTIC_INDEX_NAME`, `TEXT_INDEX_NAME`, and `AUTOCOMPLETE_INDEX_NAME` constants default to the three `quickstart_*` names. For every index you created under a collision name, edit the matching constant in the copy before handing it over, and say which ones you changed. Skip this and the script stops on the conflicting index rather than reusing the one the user watched you build.

Then tell the user:
> "Your script is at `<destination path>`. Set `MONGODB_URI` to your connection string and it runs against `sample_mflix.movies`. It reads `MDB_MCP_CONNECTION_STRING` too if that is already exported for the MCP server. To point it at your own data, change the `DB_NAME` and `COLLECTION_NAME` variables at the top. Because the script hard-codes the sample schema (`plot`, `genres`, and `title`), also update the index definitions, the `$project` stages, and the query strings to match your own field names."

## Troubleshooting

**`sample_mflix` not found**
- Load it from Atlas UI: cluster → three-dot menu → Load Sample Dataset
- If there is no Load Sample Dataset option, the cluster is not on Atlas cloud and this walkthrough does not apply. Return to Step 0.2.

**Deployment turns out not to be Atlas cloud mid-walkthrough**
- Stop rather than improvise a substitute. The Atlas UI sample-data loader is unavailable, and `autoEmbed` index creation fails without the right image or MongoDB version, `mongot`, and Voyage AI keys.
- Give the user the two options in Step 0.2: move to an Atlas cloud cluster, or leave the walkthrough and build search on their own data through the main `SKILL.md` workflow with manual embeddings. Do not offer to start a local deployment — they are already running MongoDB somewhere.

**Index stuck in Building state**
- Normal for large collections — check status with `collection-indexes`
- autoEmbed initial sync on 21K movies typically takes 2–5 minutes

**`$rankFusion` error**
- Run `db-stats` to check the MongoDB version.
- If below 8.0, tell the user: "Hybrid search requires MongoDB 8.0 or later — your cluster is on [version]. You can upgrade in Atlas, or we can wrap up here with what you've already built." Then proceed to Wrap Up.

**autoEmbed index creation fails**
- Do **not** tell the user they need an M10+ dedicated cluster — autoEmbed is not restricted to dedicated tiers. Free and Flex clusters can use it.
- Most likely cause is the tier index cap: **3** total search/vector indexes on Free, **10** on Flex, counting indexes already on the collection. See Step 3a.3 ①.
- Check `autoEmbed` isn't sharing an index definition with a `vector` type field — the two cannot coexist in the same index, and MongoDB throws an exception if both are present.
- Confirm the field `type` and `modality` weren't being edited on an existing index — those two are immutable after creation (other settings, and adding/deleting `autoEmbed` and `filter` fields, are fine).

**autoEmbed index shows `Stale` status**
- This is a disk-space pause, not a failure. Embedding generation resumes on its own once space is freed.
- On dedicated (`M10+`) clusters, enable **storage auto-scaling**: Atlas → cluster → Edit Configuration → Storage. See Step 3a.3 ②.

**No results returned**
- Check index name matches exactly — typos return no results silently
- Check index status is READY, not Building

**`$vectorSearch` returns an error (not just empty results)**
- Run `collection-indexes` to confirm the index exists
- If missing, the index needs to be created — return to the relevant creation step
vector-search.md 18.7 KB
# Vector Search - Indexing and Querying

**Scope**: This guide covers configuring MongoDB Vector Search indexes and constructing queries for semantic similarity search where the user **brings their own pre-generated embeddings**. For hybrid search (combining lexical and vector search), see `hybrid-search.md`. If the user wants MongoDB to generate and manage embeddings automatically (no embedding code), see `automated-embedding.md` instead.

## Table of Contents

- [Vector Search Index Definition](#vector-search-index-definition)
- [Index Configuration Parameters](#index-configuration-parameters)
- [Filter Fields](#filter-fields)
- [Query Construction](#query-construction)
- [Query Optimization](#query-optimization)

---

## Vector Search Index Definition

### Syntax

MongoDB Vector Search index definitions have the following structure:

```javascript
{
  "fields": [
    {
      "type": "vector",
      "path": "<field-to-index>",
      "numDimensions": <number-of-dimensions>,
      "similarity": "euclidean | cosine | dotProduct",
      "quantization": "none | scalar | binary",  // Optional
      "hnswOptions": {  // Optional (Preview feature)
        "maxEdges": <number-of-connected-neighbors>,
        "numEdgeCandidates": <number-of-nearest-neighbors>
      }
    },
    {
      "type": "filter",  // Optional: for pre-filtering
      "path": "<field-to-index>"
    }
  ]
}
```

**Note**: The exact syntax for creating indexes varies by driver/interface. The above shows the core index definition structure that applies across all methods.

### Basic Definition

Most vector search indexes only need the vector field:

```javascript
{
  "fields": [
    {
      "type": "vector",
      "path": "<embedding-field>",
      "numDimensions": <number>,
      "similarity": "<similarity-function>"
    }
  ]
}
```

---

## Index Configuration Parameters

### Required: numDimensions

**Definition**: Number of dimensions in your vector embeddings. MongoDB enforces this at both index-time and query-time.

**Constraints**:
- Must be less than or equal to 8192
- For int1 (binary) vectors: MUST be a multiple of 8
- For int8 vectors: 1 to 8192
- For float32 vectors: 1 to 8192

**How to Determine**:
- The embedding model determines this value
- It MUST match the actual dimension count of your vectors
- Cannot be changed after index creation (requires dropping and recreating index)

**Example - Voyage AI Models**:
- voyage-3-large: 2048 dimensions
- voyage-4: Configurable output dimensions (256, 512, 1024, 2048, 4096)

---

### Required: similarity

**Definition**: The similarity function used to compare vectors and rank results.

**Available Options**:

| Similarity | Score Formula | Score Range | Best For | Requirements |
|-----------|---------------|-------------|----------|--------------|
| `cosine` | `(1 + cosine(v1,v2)) / 2` | [0, 1] | Most embedding models, normalized vectors | Cannot use zero-magnitude vectors |
| `dotProduct` | `(1 + dotProduct(v1,v2)) / 2` | [0, 1] | **Most efficient** - angle + magnitude | Vectors MUST be normalized to unit length |
| `euclidean` | `1 / (1 + euclidean(v1,v2))` | [0, 1] | Spatial/geometric similarity | **REQUIRED** for int1 (binary) quantized vectors |

**Decision Process**:
1. Check your embedding model documentation for recommended similarity function
2. If model produces normalized vectors -> use `dotProduct` (fastest)
3. If model does NOT normalize vectors -> use `cosine`
4. If using binary quantization (int1) -> MUST use `euclidean`
5. When uncertain -> start with `dotProduct` and normalize your vectors

**Notes**:
- All functions return scores in range [0, 1] where 1 = most similar
- `dotProduct` is most efficient but requires normalized vectors
- Check embedding model documentation for recommendations

---

### Optional: quantization

**Definition**: Automatic vector compression to reduce storage and improve query speed at the cost of some accuracy.

**Syntax**:
```javascript
{
  "type": "vector",
  "path": "<field>",
  "numDimensions": <number>,
  "similarity": "<function>",
  "quantization": "none | scalar | binary"
}
```

**Options**:

| Type | Compression | Accuracy | Storage | Use Case |
|------|-------------|----------|---------|----------|
| `none` | 1x (no compression) | Highest | Full size | Maximum accuracy needed, small datasets (less than 1M vectors) |
| `scalar` | 4x | High | 4x smaller | Good balance for most cases (1M-10M+ vectors) |
| `binary` | 4-8x | Good | Maximum compression | Large datasets (10M+ vectors), speed priority |

**Important Rules**:
- `none`: Default if omitted. Use for pre-quantized vectors (int1, int8)
- `scalar`: Transforms float32/double values to 1-byte integers
- `binary`: Transforms values to single bit. numDimensions MUST be multiple of 8
- Binary quantization REQUIRES `euclidean` similarity
- Only use with float32 or double vectors (NOT with pre-quantized int1/int8)

**Example**:
```javascript
{
  "type": "vector",
  "path": "plot_embedding",
  "numDimensions": 1536,
  "similarity": "cosine",
  "quantization": "scalar"
}
```

---

### Optional: hnswOptions (Preview Feature)

**Definition**: Parameters for the Hierarchical Navigable Small Worlds graph construction algorithm.

**Warning**: Modifying default values might negatively impact your index and queries. Use with caution.

**Syntax**:
```javascript
{
  "type": "vector",
  "path": "<field>",
  "numDimensions": <number>,
  "similarity": "<function>",
  "hnswOptions": {
    "maxEdges": <16-64>,  // Default: 16
    "numEdgeCandidates": <100-3200>  // Default: 100
  }
}
```

**Parameters**:

**maxEdges** (16-64, default: 16):
- Maximum number of connections per node in the graph
- Higher values:
  - Better recall (finds more relevant results)
  - Slower queries (more neighbors to evaluate)
  - More memory usage (more connections stored)
  - Slower indexing (more neighbors to adjust)

**numEdgeCandidates** (100-3200, default: 100):
- Maximum nodes evaluated to find best connections for new nodes
- Higher values:
  - Better graph quality (improves search accuracy)
  - Can negatively affect query latency

**Recommendation**: Leave at defaults unless you have specific performance requirements and understand the trade-offs.

---

## Filter Fields

**Performance**: Filtering before similarity computation is much faster than post-filtering with `$match`.

**Recommendation**: Use pre-filtering whenever possible for best performance. Reserve post-filtering for complex or ad-hoc queries.

### Important Notes for Pre-filtering

**Definition**: Additional fields indexed to enable pre-filtering before vector similarity computation. This narrows the search scope and improves performance.
**Use Case**: You have multi-tenant data that needs isolation or you need to filter by specific criteria (e.g., category, date range, user ID), by exact values (category = "Action"), or by range (year >= 2020) BEFORE computing vector similarity.
**Supported Field Types**: boolean, date, objectId, numeric (int32, int64, double), string, UUID, and arrays of these types.
**Requirements**: You must add fields as type "filter" in your index definition to use them in the filter option. Fields not indexed cannot be used for pre-filtering.
**Supported Filter Operators**: $eq, $ne, $gt, $lt, $gte, $lte, $in, $nin, $exists, $and, $or, $not, $nor
**Pre-filtering does NOT affect scores**: The vectorSearchScore returned for documents is based only on vector similarity, not on how well they matched the filter criteria.

---

### Syntax

```javascript
{
  "fields": [
    {
      "type": "vector",
      "path": "embedding",
      "numDimensions": 1024,
      "similarity": "cosine"
    },
    {
      "type": "filter",
      "path": "category"  // String field for filtering
    },
    {
      "type": "filter",
      "path": "year"  // Numeric field for filtering
    }
  ]
}
```

---

### Pre-Filter Examples

**Index with filter fields**:
```javascript
{
  "fields": [
    {
      "type": "vector",
      "path": "plot_embedding",
      "numDimensions": 2048,
      "similarity": "dotProduct"
    },
    {
      "type": "filter",
      "path": "genres"  // String or array of strings
    },
    {
      "type": "filter",
      "path": "year"  // Numeric field
    }
  ]
}
```

**Query with single filter**:
```javascript
{
  $vectorSearch: {
    queryVector: [<array-of-numbers>],
    path: "plot_embedding",
    filter: {
      genres: { $eq: "Action" }
    },
    numCandidates: 150,
    limit: 10
  }
}
```

**Query with multiple filters using $and**:
```javascript
{
  $vectorSearch: {
    queryVector: [<array-of-numbers>],
    path: "plot_embedding",
    filter: {
      $and: [
        { genres: "Action" },
        { year: { $gte: 2020 } }
      ]
    },
    numCandidates: 150,
    limit: 10
  }
}
```

**Short form of $eq** (recommended):
```javascript
{
  $vectorSearch: {
    queryVector: [<array-of-numbers>],
    path: "plot_embedding",
    filter: {
      genres: "Action",  // Equivalent to { genres: { $eq: "Action" } }
      year: { $gte: 2020 }
    },
    numCandidates: 150,
    limit: 10
  }
}
```

---

### Important Notes for Post-Filtering

**Definition**: Filtering after vector similarity computation. 
**Use Case**: Use post-filtering when you need to filter by criteria that are not known until query time, or when you need to combine vector search with other aggregation stages. No need to index fields.
**Advantages**: More flexible, can combine with other aggregation stages, no need to index fields.
**Performance**: Slower than pre-filtering, computes similarity for all candidates first.

---

### Post-Filter Examples

**Post-filtering with $match**

For ad-hoc filters or complex logic not indexed as filter fields, use `$match` after `$vectorSearch`:

```javascript
db.collection.aggregate([
  {
    $vectorSearch: {
      index: "vector_index",
      path: "plot_embedding",
      queryVector: [<array>],
      numCandidates: 150,
      limit: 50  // Get more candidates for post-filtering
    }
  },
  {
    $match: {
      category: "Electronics",
      "reviews.rating": { $gte: 4.5 }  // Complex nested field
    }
  },
  { $limit: 10 }
])
```

---

## Query Construction

### $vectorSearch Stage

**Definition**: The `$vectorSearch` stage performs semantic search for a query vector on indexed vector fields. It must be the first stage in an aggregation pipeline.

**Requirements**:
- Atlas cluster running MongoDB v6.0.11, v7.0.2, or later
- A vector search index on the collection with vector-type fields
- `$vectorSearch` MUST be the first stage in the pipeline

---

### Basic Query Syntax

```javascript
{
  "$vectorSearch": {
    "index": "<index-name>",
    "path": "<field-to-search>",
    "queryVector": [<array-of-numbers>],
    "numCandidates": <number-of-candidates>,
    "limit": <number-of-results>,
    "filter": {<filter-specification>},  // Optional
    "exact": true | false  // Optional
  }
}
```

---

### Required Fields

**index** (String, Required):
- Name of the MongoDB Vector Search index to use
- MongoDB returns no results if the index name is misspelled or doesn't exist
- Must match the name specified when creating the index

**path** (String, Required):
- Name of the indexed vector field to search
- Must be a field indexed as type "vector" in your index definition
- Use dot notation for nested fields (e.g., "metadata.embedding")

**queryVector** (Array of Numbers, Required):
- Array of numbers representing your query vector
- Can be float32, BSON BinData float32, or BSON BinData int1/int8
- Array size MUST match numDimensions specified in the index
- You must use the same embedding model that generated the indexed vectors

**limit** (Integer, Required):
- Number of documents to return in results
- Must be an integer value
- Cannot exceed numCandidates if numCandidates is specified

---

### Conditional Fields

**numCandidates** (Integer, Conditional):
- Number of nearest neighbors to use during ANN search
- Required if `exact` is false or omitted
- Must be less than or equal to 10000
- Cannot be less than `limit`
- Recommended: Set to at least 20x the `limit` value for good recall

**Example**:
```javascript
{
  $vectorSearch: {
    queryVector: [<array>],
    path: "embedding",
    numCandidates: 150,  // 15x the limit
    limit: 10
  }
}
```

---

### Optional Fields

**filter** (Object, Optional): See Filter Fields section for details and examples

**exact** (Boolean, Optional):
- Set to `true` for ENN (Exact Nearest Neighbor) search
- Set to `false` or omit for ANN (Approximate Nearest Neighbor) search
- Default: false

**ENN vs ANN**:
- **ANN (default)**: Faster, uses HNSW algorithm, good for large datasets, 90-95% recall
- **ENN**: Exhaustive search, guaranteed exact matches, slower, use for small datasets (less than 10K docs) or measuring accuracy baseline

---

### Complete Query Examples

**Basic ANN query**:
```javascript
db.collection.aggregate([
  {
    $vectorSearch: {
      index: "vector_index",
      path: "plot_embedding",
      queryVector: [<1536-dimension-array>],
      numCandidates: 150,
      limit: 10
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      plot: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

**ANN query with pre-filtering**:
```javascript
db.collection.aggregate([
  {
    $vectorSearch: {
      index: "vector_index",
      path: "plot_embedding",
      queryVector: [<2048-dimension-array>],
      filter: {
        $and: [
          { year: { $gte: 1955 } },
          { year: { $lt: 1975 } }
        ]
      },
      numCandidates: 150,
      limit: 10
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      year: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

**ENN query (exact search)**:
```javascript
db.collection.aggregate([
  {
    $vectorSearch: {
      index: "vector_index",
      path: "plot_embedding",
      queryVector: [<2048-dimension-array>],
      exact: true,
      limit: 10
    }
  },
  {
    $project: {
      _id: 0,
      title: 1,
      score: { $meta: "vectorSearchScore" }
    }
  }
])
```

---

### Retrieving Vector Search Scores

Use `$meta: "vectorSearchScore"` in a `$project` stage to include similarity scores:

```javascript
{
  $project: {
    title: 1,
    score: { $meta: "vectorSearchScore" }
  }
}
```

**Important**:
- Scores are in range [0, 1] where 1 = most similar
- You can ONLY use `vectorSearchScore` after a `$vectorSearch` stage

## Query Optimization

### numCandidates Tuning

**Definition**: The `numCandidates` parameter controls the trade-off between recall (finding relevant results) and query performance in ANN searches.

**Rule of Thumb**: A good starting point is 20x your `limit` value. You can adjust between 10-20x (or higher) based on your recall and performance requirements.

**Example**:
```javascript
{
  $vectorSearch: {
    queryVector: [<array>],
    path: "embedding",
    numCandidates: 200,  // 20x the limit — good starting point; tune between 10-50x based on recall and latency requirements
    limit: 10
  }
}
```

---

### When to Adjust numCandidates

**Increase when**:
- Search results miss relevant documents
- Large dataset (millions of vectors)
- Using quantized vectors (int8 or int1)
- Heavy pre-filtering is applied

**Decrease when**:
- Queries are too slow and results are already good
- Small dataset (thousands of vectors)
- Speed is more important than perfect recall

**Note on low limit values**: A very low limit (e.g., 5) may need proportionally higher numCandidates (e.g., 40x) to maintain recall.

### Test and Measure

- Start with 20x limit and run sample queries
- Check result quality and query latency
- Adjust up or down based on your accuracy vs performance requirements

---

### ANN vs ENN Search

**ANN (Approximate Nearest Neighbor)**:
- Default search method
- Uses HNSW algorithm for fast approximate search
- Typically 90-95% recall (finds 90-95% of exact matches)
- Much faster than ENN for large datasets
- Requires `numCandidates` parameter

**Use ANN when**:
- You have production queries
- Dataset is large (more than 10K documents)
- 90-95% recall is acceptable
- Query speed is important

**ENN (Exact Nearest Neighbor)**:
- Exhaustive search of all indexed vectors
- Guaranteed to find exact best matches
- Much slower than ANN
- Set `exact: true` in query
- Does NOT require `numCandidates` parameter
- Uses full-fidelity vectors even when quantization is enabled

**Use ENN when**:
- Measuring accuracy baseline (ground truth for testing)
- Collection has less than 10K documents
- Very selective filters (less than 5% of data matches)
- You need guaranteed best matches

### Parallel Query Execution

MongoDB Vector Search parallelizes query execution across segments when running on dedicated search nodes, which can improve response time for queries on large datasets.

**Notes**:
- Works automatically on dedicated search nodes
- High-CPU systems provide more performance improvement
- Not guaranteed for every query (e.g., when too many concurrent queries are queued)
- May cause slight inconsistencies in results for successive identical queries

**If you see inconsistent results**: Increase `numCandidates` to improve consistency.

---

### Best Practices Summary

1. **Start with numCandidates = 20x limit**: Provides good balance of recall and performance
2. **Use pre-filtering when possible**: Index filter fields for known filtering criteria
3. **Choose appropriate similarity function**: Match your embedding model's recommendations
4. **Consider quantization for large datasets**: Use scalar or binary quantization for 10M+ vectors
5. **Use ANN for production**: Reserve ENN for testing/small datasets
6. **Test with your data**: Run sample queries and measure recall vs latency
7. **Monitor and adjust**: Use query performance metrics to tune numCandidates
8. **Match query vectors to index**: Use the same embedding model and dimensions

---

## Vector Search on Views

Version requirements, supported stages, limitations, and troubleshooting are identical to Atlas Search on Views — see `lexical-search-indexing.md`. The difference is using a `vectorSearch`-type index and querying with `$vectorSearch`.

**Example: partial index (exclude documents without embeddings)**
```javascript
db.createView("moviesWithEmbeddings", "embedded_movies", [
  {
    $match: {
      $expr: { $ne: [{ $type: "$plot_embedding_voyage_3_large" }, "missing"] }
    }
  }
])

db.moviesWithEmbeddings.createSearchIndex(
  "embeddingsIndex",
  "vectorSearch",
  {
    "fields": [
      {
        "type": "vector",
        "numDimensions": 2048,
        "path": "plot_embedding_voyage_3_large",
        "similarity": "cosine"
      }
    ]
  }
)

// 8.1+: query view directly; 8.0: query source collection using index name
db.moviesWithEmbeddings.aggregate([
  {
    $vectorSearch: {
      index: "embeddingsIndex",
      path: "plot_embedding_voyage_3_large",
      queryVector: [<query-vector-2048-dimensions>],
      numCandidates: 100,
      limit: 10
    }
  }
])
```

---
scripts/
quickstart_complete.py 12.4 KB
#!/usr/bin/env python3
# /// script
# dependencies = [
#   "pymongo>=4.6.0",
# ]
# ///

# MongoDB Search Quickstart — Complete Script
# ─────────────────────────────────────────────────────────────
# Written for the Atlas `sample_mflix.movies` sample collection. The
# schema is hard-coded throughout: the `plot`, `genres`, and `title`
# fields, the index definitions, and the sample query text.
#
# The connection string comes from the environment: set MONGODB_URI, or
# MDB_MCP_CONNECTION_STRING, which the MongoDB MCP server already uses.
#
# To run against your own data, change the two values below AND
# update the index definitions, `$project` stages, and query strings
# to match your own field names.

DB_NAME = "sample_mflix"
COLLECTION_NAME = "movies"

# Index names. The walkthrough uses these defaults, but creates `<name>_2` when
# the default is already taken by an incompatible definition. If that happened,
# set the matching constant to the name it created, so this script reuses that
# index instead of stopping on the conflicting one.
SEMANTIC_INDEX_NAME = "quickstart_semantic"
TEXT_INDEX_NAME = "quickstart_text"
AUTOCOMPLETE_INDEX_NAME = "quickstart_autocomplete"

INDEX_WAIT_TIMEOUT_SECONDS = 600

# ─────────────────────────────────────────────────────────────

import os
import time
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel

CONNECTION_STRING = (os.environ.get("MONGODB_URI")
                     or os.environ.get("MDB_MCP_CONNECTION_STRING"))

if not CONNECTION_STRING:
    raise SystemExit("\n  ERROR: no connection string. Set MONGODB_URI (or"
                     " MDB_MCP_CONNECTION_STRING) to your cluster's SRV"
                     " string, then rerun.")

client = MongoClient(CONNECTION_STRING)
db = client[DB_NAME]
collection = db[COLLECTION_NAME]

def fail(message):
    print(f"\n  ERROR: {message}")
    client.close()
    raise SystemExit(1)

def wait_for_index(name):
    print(f"  Waiting for index '{name}' to be ready...", end="", flush=True)
    deadline = time.monotonic() + INDEX_WAIT_TIMEOUT_SECONDS
    while True:
        indexes = list(collection.list_search_indexes(name))
        if not indexes:
            fail(f"Index '{name}' does not exist.")
        status = indexes[0].get("status")
        if status == "READY":
            print(" ready.")
            return
        if status == "STALE":
            fail(f"Index '{name}' is stale because embedding sync is paused. "
                 "Free disk space, wait for READY, then rerun.")
        if status == "FAILED":
            fail(f"Index '{name}' failed to build. Check the tier index cap"
                 " (3 on Free, 10 on Flex) and the index definition.")
        if time.monotonic() > deadline:
            fail(f"Index '{name}' is still '{status}' after"
                 f" {INDEX_WAIT_TIMEOUT_SECONDS}s. Check its status in Atlas,"
                 " then rerun.")
        print(".", end="", flush=True)
        time.sleep(5)

def covers(expected, actual):
    # True when `actual` contains everything `expected` asks for. Atlas adds
    # its own defaults to a stored definition, so an exact match is too strict.
    if isinstance(expected, dict):
        # A field can be stored as a list of types (a multi-type field), which
        # still satisfies a single expected type.
        if isinstance(actual, list):
            return any(covers(expected, candidate) for candidate in actual)
        return (isinstance(actual, dict)
                and all(k in actual and covers(v, actual[k])
                        for k, v in expected.items()))
    if isinstance(expected, list):
        return (isinstance(actual, list)
                and all(any(covers(item, candidate) for candidate in actual)
                        for item in expected))
    return expected == actual

def check_definition(name, expected):
    indexes = list(collection.list_search_indexes(name))
    if not indexes:
        fail(f"Index '{name}' does not exist.")
    actual = indexes[0].get("latestDefinition", {})
    if not covers(expected, actual):
        fail(f"An index named '{name}' already exists, but its definition does"
             " not match the one this script needs, so the queries below would"
             " fail. An index created by another route (for example the MCP"
             " walkthrough) can omit fields this script queries. Drop"
             f" '{name}' in Atlas and rerun, or point the matching"
             " *_INDEX_NAME constant at the top of this script at a name that"
             f" is free or already correct.\n  Existing definition: {actual}")

def ensure_index(model, name, definition):
    try:
        collection.create_search_index(model)
    except Exception as e:
        if "already exists" not in str(e):
            fail(f"Could not create index '{name}': {e}")
        print("  Index already exists — checking its definition.")
        check_definition(name, definition)
    wait_for_index(name)

def print_results(results, fields=["title", "plot"]):
    for i, doc in enumerate(results, 1):
        print(f"\n  {i}. {doc.get('title', 'N/A')}")
        if "score" in doc:
            print(f"     Score: {round(doc['score'], 3)}")
        if "plot" in fields and doc.get("plot"):
            print(f"     Plot:  {doc['plot'][:120]}...")
        if "genres" in doc:
            print(f"     Genres: {doc.get('genres', [])}")

# ─────────────────────────────────────────────────────────────
# 1. CREATE AUTO EMBEDDING INDEX (Semantic Search)
# ─────────────────────────────────────────────────────────────
print("\n── SEMANTIC SEARCH (Auto Embedding) ──────────────────")
print("Creating autoEmbed index on 'plot' field...")

semantic_definition = {
    "fields": [
        {
            "type": "autoEmbed",
            "modality": "text",
            "path": "plot",
            "model": "voyage-4"
        },
        {
            "type": "filter",
            "path": "genres"
        }
    ]
}

ensure_index(
    SearchIndexModel(
        definition=semantic_definition,
        name=SEMANTIC_INDEX_NAME,
        type="vectorSearch"
    ),
    SEMANTIC_INDEX_NAME,
    semantic_definition
)

# Run semantic query
print("\nQuery: 'a story about growing up'")
results = list(collection.aggregate([
    {
        "$vectorSearch": {
            "index": SEMANTIC_INDEX_NAME,
            "path": "plot",
            "query": "a story about growing up",
            "numCandidates": 100,
            "limit": 3
        }
    },
    {
        "$project": {
            "_id": 0,
            "title": 1,
            "plot": 1,
            "score": { "$meta": "vectorSearchScore" }
        }
    }
]))
print_results(results)

# Run filtered semantic query
print("\nFiltered query: 'a story about growing up' + Drama only")
results = list(collection.aggregate([
    {
        "$vectorSearch": {
            "index": SEMANTIC_INDEX_NAME,
            "path": "plot",
            "query": "a story about growing up",
            "filter": { "genres": { "$eq": "Drama" } },
            "numCandidates": 150,
            "limit": 3
        }
    },
    {
        "$project": {
            "_id": 0,
            "title": 1,
            "genres": 1,
            "score": { "$meta": "vectorSearchScore" }
        }
    }
]))
print_results(results, fields=["title", "genres"])

# ─────────────────────────────────────────────────────────────
# 2. CREATE TEXT SEARCH INDEX (Keyword Search)
# ─────────────────────────────────────────────────────────────
print("\n── KEYWORD SEARCH (Atlas Search) ─────────────────────")
print("Creating text search index on 'title', 'plot', 'genres'...")

text_definition = {
    "mappings": {
        "dynamic": False,
        "fields": {
            "title": { "type": "string" },
            "plot": { "type": "string" },
            "genres": { "type": "token" }
        }
    }
}

ensure_index(
    SearchIndexModel(
        definition=text_definition,
        name=TEXT_INDEX_NAME
    ),
    TEXT_INDEX_NAME,
    text_definition
)

# Run keyword query
print("\nKeyword query: 'space adventure'")
results = list(collection.aggregate([
    {
        "$search": {
            "index": TEXT_INDEX_NAME,
            "text": {
                "query": "space adventure",
                "path": ["title", "plot"]
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "title": 1,
            "plot": 1,
            "score": { "$meta": "searchScore" }
        }
    },
    { "$limit": 3 }
]))
print_results(results)

# Run fuzzy query
print("\nFuzzy query: 'sapce adventre' (intentional typos)")
results = list(collection.aggregate([
    {
        "$search": {
            "index": TEXT_INDEX_NAME,
            "text": {
                "query": "sapce adventre",
                "path": ["title", "plot"],
                "fuzzy": { "maxEdits": 1 }
            }
        }
    },
    {
        "$project": {
            "_id": 0,
            "title": 1,
            "score": { "$meta": "searchScore" }
        }
    },
    { "$limit": 3 }
]))
print_results(results, fields=["title"])

# Autocomplete needs 'title' typed as autocomplete, which the text index does
# not provide. Use a dedicated index, matching the walkthrough's MCP route.
print("\nCreating autocomplete index on 'title'...")

autocomplete_definition = {
    "mappings": {
        "dynamic": False,
        "fields": {
            "title": { "type": "autocomplete", "tokenization": "edgeGram" }
        }
    }
}

ensure_index(
    SearchIndexModel(
        definition=autocomplete_definition,
        name=AUTOCOMPLETE_INDEX_NAME
    ),
    AUTOCOMPLETE_INDEX_NAME,
    autocomplete_definition
)

# Run autocomplete
print("\nAutocomplete query: 'inc'")
results = list(collection.aggregate([
    {
        "$search": {
            "index": AUTOCOMPLETE_INDEX_NAME,
            "autocomplete": { "query": "inc", "path": "title" }
        }
    },
    { "$project": { "_id": 0, "title": 1 } },
    { "$limit": 5 }
]))
for doc in results:
    print(f"  - {doc['title']}")

# ─────────────────────────────────────────────────────────────
# 3. HYBRID SEARCH ($rankFusion)
# ─────────────────────────────────────────────────────────────
print("\n── HYBRID SEARCH ($rankFusion) ───────────────────────")
print("Query: 'a story about growing up' (semantic 70% + keyword 30%)")

try:
    results = list(collection.aggregate([
        {
            "$rankFusion": {
                "input": {
                    "pipelines": {
                        "semanticPipeline": [
                            {
                                "$vectorSearch": {
                                    "index": SEMANTIC_INDEX_NAME,
                                    "path": "plot",
                                    "query": "a story about growing up",
                                    "numCandidates": 100,
                                    "limit": 20
                                }
                            }
                        ],
                        "keywordPipeline": [
                            {
                                "$search": {
                                    "index": TEXT_INDEX_NAME,
                                    "text": {
                                        "query": "coming of age",
                                        "path": "plot"
                                    }
                                }
                            },
                            { "$limit": 20 }
                        ]
                    }
                },
                "combination": {
                    "weights": {
                        "semanticPipeline": 0.7,
                        "keywordPipeline": 0.3
                    }
                }
            }
        },
        { "$project": { "_id": 0, "title": 1, "plot": 1 } },
        { "$limit": 5 }
    ]))
    print_results(results)
except Exception as e:
    message = str(e)
    if "Unrecognized pipeline stage name: '$rankFusion'" in message:
        print("  $rankFusion requires MongoDB 8.0+. This cluster does not"
              " support it, so hybrid search was skipped.")
    else:
        fail(f"Hybrid search query failed: {message}")

print("\n── Done! ─────────────────────────────────────────────")
print("This script targets the sample_mflix.movies schema. To use your")
print("own data, set MONGODB_URI (or MDB_MCP_CONNECTION_STRING), then")
print("change DB_NAME and COLLECTION_NAME at the top and adjust the")
print("index definitions, $project stages, and query strings to match")
print("your own field names.")

client.close()

License (Apache-2.0)

View full license text
Licensed under the Apache License, Version 2.0. See https://github.com/mongodb/agent-skills/blob/main/LICENSE