Generated banner for Mongodb Search And AI
Generated logo for Mongodb Search And AI

Mongodb Search And AI

MongoDBOfficialPublished by MongoDB

  • Skill
  • Tool integration
  • Data and AI
  • Apache-2.0
  • Low risk
  • Has scripts

From the author

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.
— the description by MongoDB

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

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/mongodb/mongodb-search-and-ai/download
  2. Unzip 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

  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

Files

references/lexical-search-indexing.md

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

  • Analyzer Selection

  • Field Types

  • Dynamic vs Explicit Mappings

  • Stored Source

  • Synonyms


Atlas Search Index Definition

Syntax
{
  "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
FieldTypeRequiredDescription
analyzerStringOptionalSpecifies 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.
searchAnalyzerStringOptionalSpecifies the analyzer to apply to query text before searching. If omitted, defaults to the analyzer option. If both omitted, defaults to Standard Analyzer.
mappingsObjectRequiredSpecifies how to index fields at different paths for this index.
mappings.dynamicBoolean or ObjectOptionalEnables 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.typeSetStringOptionalReferences 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.fieldsObjectConditionalSpecifies 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.
numPartitionsIntegerOptionalSpecifies 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.
analyzersArray of Custom AnalyzersOptionalSpecifies the custom analyzers to use in this index. Reference by name in analyzer, searchAnalyzer, or field-level analyzer options.
storedSourceBoolean or ObjectOptionalSpecifies 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.
synonymsArray of Synonym Mapping DefinitionOptionalSpecifies synonym mappings to use in your index. An index definition can have only one synonym mapping.
typeSetsArray of ObjectsOptionalSpecifies the typeSets to use for dynamic mappings.
typeSets.[n].nameStringRequiredSpecifies the name of the typeSet configuration.
typeSets.[n].typesArray of ObjectsRequiredSpecifies the field types to index automatically using dynamic mappings.
typeSets.[n].types.[n].typeStringRequiredSpecifies the field type to automatically index (e.g., "string", "number", "date").
Basic Definition

Most indexes only need the mappings configuration:

{
  "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:

AnalyzerUse CaseExample
lucene.standardGeneral text search (default)"The quick brown fox" → ["quick", "brown", "fox"]
lucene.simpleLowercase, no special chars"Hello-World!" → ["hello", "world"]
lucene.keywordExact matching, facets"Action" → ["Action"]
lucene.whitespaceSplit on spaces only"first-class" → ["first-class"]
Language-specificStemming, stop wordslucene.english, lucene.spanish

Index Analyzer (Applied at Index Time)

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

// 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:

// 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:

// 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:

// 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):

// 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
TypeWhen to UseRequired FieldsOptional Fields (with valid values)Notes
stringFull-text search, phrase matching, fuzzy searchtypeanalyzer, searchAnalyzer, indexOptions: "docs" or "freqs" or "positions" or "offsets", store: true or false, multiDefault for text. For sorting use token instead.
tokenSort/facet on text, exact matchingtypenormalizer: "lowercase" or "none" (default: "none")Required for sorting or faceting strings. Max 8181 chars.
autocompleteSearch-as-you-type, typeahead, partial or substring matchingtypeanalyzer, tokenization: "edgeGram" or "rightEdgeGram" or "nGram" (default: "edgeGram"), minGrams (default: 2), maxGrams (default: 15), foldDiacritics: true or falseNot included in "dynamic: true". Recommend maxGrams ≤ 15.
booleanTrue/false filterstypeNoneIncluded in "dynamic: true".
dateDate ranges, timestampstypeNoneIncluded in "dynamic: true".
numberNumeric queries, ranges, sortingtyperepresentation: "int64" or "double" (default: "double"), indexIntegers: true or false, indexDoubles: true or falseIncluded in "dynamic: true". Use int64 for large integers.
objectIdQuery by _idtypeNoneIncluded in "dynamic: true". Standard MongoDB ObjectIds.
uuidUUID identifierstypeNoneIncluded in "dynamic: true". BSON Binary Subtype 4.
geoLocation search, geographic queriestypeindexShapes: true or false (default: false)Included in "dynamic: true". Requires GeoJSON. Set indexShapes=true for polygons.
embeddedDocumentsSearch in arrays of objects, independent scoringtypedynamic: 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.
vectorLexical prefilters for semantic searchtype, numDimensions (1-8192), similarity: "cosine" or "dotProduct" or "euclidean"quantization: "none" or "scalar" or "binary" (default: "none"), hnswOptions.maxEdges: 16-64, hnswOptions.numEdgeCandidates: 100-3200Not included in "dynamic: true". For hybrid search. See vector-search.md and hybrid-search.md.

Field definition structure:

{
  "mappings": {
    "fields": {
      "<field-name>": {
        "type": "<field-type>",
        // type-specific options here
      }
    }
  }
}

Multiple types on same field:

"<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:

{
  "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:

{
  "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):

{
  "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:

{
  "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:

{
  "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:

{
  "storedSource": {
    "exclude": ["largeTextField", "unusedField"]
  }
}

Store all fields:

{
  "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):

db.synonyms.insertMany([
  {
    "mappingType": "equivalent",
    "synonyms": ["car", "vehicle", "automobile"]
  },
  {
    "mappingType": "equivalent",
    "synonyms": ["happy", "joyful", "glad"]
  }
])

For one-way synonyms (input maps to synonyms only):

db.synonyms.insertMany([
  {
    "mappingType": "explicit",
    "input": ["pants"],
    "synonyms": ["trousers", "slacks"]
  }
])
  1. Add synonym mapping to index definition:

{
  "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)

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+

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 or MongoDB.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download mongodb-search-and-ai.zip