Mongodb Search And AI
MongoDBOfficialPublished by MongoDB
- Skill
- Tool integration
- Data and AI
- Apache-2.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive framework for integrating search capabilities into MongoDB applications. It covers the full spectrum of search technologies available in MongoDB, including lexical full-text search, semantic vector search, and hybrid approaches. The skill guides users through the entire lifecycle of search implementation: from initial discovery and use-case validation to index configuration, query construction, and performance optimization. It emphasizes best practices, such as choosing the right search type based on specific business needs, and provides structured workflows for both manual and automated embedding scenarios.
What it does
- Helps users choose between Atlas Search, Vector Search, and Hybrid Search.
- Provides workflows for creating and managing search indexes.
- Assists in constructing complex aggregation pipelines for search queries.
- Offers guidance on using Automated Embedding for semantic search without custom code.
- Explains how to implement hybrid search using rank-based or score-based fusion.
- Validates search configurations against cluster requirements and best practices.
When to use it
- When you need to add full-text, semantic, or hybrid search to a MongoDB collection.
- When you are unsure which MongoDB search technology best fits your specific data and use case.
- When you need to optimize existing search queries or troubleshoot index performance.
- When you want to implement RAG or semantic search but lack existing embedding infrastructure.
- When you need to combine keyword-based filtering with semantic similarity.
Advantages
- Prevents common anti-patterns like using inefficient regex or text operators.
- Ensures search implementations are aligned with specific MongoDB cluster capabilities.
- Simplifies complex search concepts into actionable, step-by-step workflows.
- Provides clear guidance on model selection for automated embeddings.
- Promotes performance-oriented index design and query construction.
Usage examples
- “How do I implement semantic search for my product catalog?”
- The agent will initiate a discovery phase to inspect your collection schema, determine if you have existing embeddings, and recommend either Automated Embedding or manual Vector Search.
- “What is the difference between Atlas Search and Vector Search?”
- The agent will explain the technical distinctions between lexical and semantic search and help you decide which is appropriate for your specific data requirements.
- “I want to combine keyword filtering with vector similarity.”
- The agent will guide you through the Hybrid Search workflow, explaining how to use lexical prefilters or fusion stages like $rankFusion.
- “Help me get started with search.”
- The agent will offer a choice between a guided tour using sample data or a discovery process to build search features directly for your own data.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/mongodb/mongodb-search-and-ai/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip mongodb-search-and-ai.zip -d .agents/skills
Documentation by MongoDB
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
Understand before building - Validate the use case to ensure you recommend the right solution
Always inspect first - Check existing indexes and schema before making recommendations
Explain before executing - Describe what indexes will be created and require explicit approval
Handle read-only scenarios - Without
create,update, ordeleteoperation tools you are in read-only mode; hand the user index JSON to create themselvesExplain 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.mdand 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-databasesandlist-collectionsto understand available dataIf the user mentions a collection, use
collection-schemato inspect field structureUse
collection-indexesto see existing indexesUse
atlas-inspect-clusterto 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:
Explain the index configuration in plain language
Show the JSON structure
Ask what the user wants to name the index
Get explicit approval: "Should I create this index?"
Use MCP's
create-indextool after approvalIn read-only mode, provide the complete index JSON for creation via the Atlas UI
Running queries:
Show the aggregation pipeline
Execute using MCP's
aggregatetoolPresent results clearly
Refining existing queries:
Ask the user to share their current query
Compare against the query patterns and best practices in the relevant reference file(s)
Propose specific improvements with before/after examples
Run the revised query with
aggregateto 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 userA 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 firstMultiple collections are relevant — ask which one they mean, unless context makes it obvious
Files
- ATTRIBUTION.mdAdded by AutoGineer845 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md8.7 KiB
- references/automated-embedding.md15.9 KiB
- references/hybrid-search.md23.1 KiB
- references/lexical-search-indexing.md19.5 KiB
- references/lexical-search-querying.md17.5 KiB
- references/quick-start.md45.1 KiB
- references/vector-search.md18.7 KiB
- scripts/quickstart_complete.pyScript13.6 KiB
references/automated-embedding.md
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
Model Selection
Index Definition
Query Construction
Item-to-Item Similarity
How It Works Internally
Billing and Free Tokens
Rate Limits
Management and Monitoring
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:
MongoDB 8.3+ with
mongotA Voyage AI API key for indexing
A Voyage AI API key for querying (recommended to use separate keys)
Keys configured in
mongotduring 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-4Large collection, cost is a concern →
voyage-4-liteHigh-stakes retrieval where accuracy matters most →
voyage-4-largeCodebase 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 below for how consumption and invoicing work.
Index Definition
Syntax
{
"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):
{
"fields": [
{
"type": "autoEmbed",
"modality": "text",
"path": "description",
"model": "voyage-4"
}
]
}With filter fields (recommended for scoped search):
{
"fields": [
{
"type": "autoEmbed",
"modality": "text",
"path": "description",
"model": "voyage-4"
},
{
"type": "filter",
"path": "category"
},
{
"type": "filter",
"path": "year"
}
]
}Creating the Index (mongosh)
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
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
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:
{
$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:
// 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
MongoDB scans all documents in the collection for the indexed text field
Sends text to the Voyage AI model in batches (uses Flex inference tier — no standard rate limits)
Stores embeddings in an internal reserved database:
__mdb_internal_searchBuilds 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:
{
_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 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(notBuildingorFailed)Verify the
pathin the query matches thepathin the index definitionVerify the
indexname 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
Requirements and compatibility
Written for: Claude Code
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Names Claude Code tools, Needs an API key, Needs Python
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- MongoDB
- Publisher
- MongoDB (Official)
- Source
- mongodb/agent-skills · skills/mongodb-search-and-ai · commit 155bb9c
- Licence
- Apache License 2.0 (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Also distributed in
- mongodb/agent-skills, mongodb/agent-skills
AutoGineer is not affiliated with or endorsed by MongoDB.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mongodb-search-and-ai.zip