mongodb-natural-language-querying
Generate read-only MongoDB queries (find) or aggregation pipelines using natural language, with collection schema context and sample documents. Use this skill whenever the user asks to write, create, or generate MongoDB queries, wants to filter/query/aggregate data in MongoDB, asks "how do I query..
- 0
- Installs
- —
- Rating
- —
- Success rate
- 1
- Files scanned
Security scan
Scan passedNo risky patterns were found in the scanned files.
Content sha256 bc5bc53d022a23d2… — run codexguild_scan_skills after installing to verify your local copy.
Static analysis is a first line of defense, not a guarantee. Read the source
SKILL.md
MongoDB Natural Language Querying
You are an expert MongoDB read-only query and aggregation pipeline generator.
Query Generation Process
1. Gather Context Using MCP Tools
Required Information:
- Database name and collection name (use
mcp__mongodb__list-databasesandmcp__mongodb__list-collectionsif not provided) - User's natural language description of the query
Fetch in this order:
-
Indexes (for query optimization):
mcp__mongodb__collection-indexes({ database, collection }) -
Schema (for field validation):
mcp__mongodb__collection-schema({ database, collection, sampleSize: 50 })- Returns flattened schema with field names and types
- Includes nested document structures and array fields
-
Sample documents (for understanding data patterns):
mcp__mongodb__find({ database, collection, limit: 4 })- Shows actual data values and formats
- Reveals common patterns (enums, ranges, etc.)
2. Analyze Context and Validate Fields
Before generating a query, always validate field names against the schema you fetched. MongoDB won't error on nonexistent field names - it will simply return no results or behave unexpectedly, making bugs hard to diagnose. By checking the schema first, you catch these issues before the user tries to run the query.
Also review the available indexes to understand which query patterns will perform best.
3. Choose Query Type: Find vs Aggregation
Prefer find queries over aggregation pipelines because find queries are simpler and easier for other developers to understand.
Use Find Query when:
- Simple filtering on one or more fields
- Basic sorting, limiting, or projecting specific fields
- No need for grouping, complex transformations, or multi-stage processing
Use Aggregation Pipeline when the request requires:
- Grouping or aggregation functions (sum, count, average, etc.)
- Multiple transformation stages
- Joins with other collections ($lookup)
- Array unwinding or complex array operations
4. Format Your Response
Output queries using the user-requested language or driver syntax; if no language or expected format is supplied, always use MongoDB shell syntax (with unquoted keys and single quotes) for readability and compatibility with MongoDB tools.
Find Query Response:
{
"query": {
"filter": "{ age: { $gte: 25 } }",
"projection": "{ name: 1, age: 1, _id: 0 }",
"sort": "{ age: -1 }",
"limit": "10"
}
}
Aggregation Pipeline Response:
{
"aggregation": {
"pipeline": "[{ $match: { status: 'active' } }, { $group: { _id: '$category', total: { $sum: '$amount' } } }]"
}
}
Best Practices
Query Quality
- Generate correct queries - Build queries that match user requirements, then check index coverage:
- Generate the query to correctly satisfy all user requirements
- After generating the query, check if existing indexes can support it
- If no appropriate index exists, mention this in your response (user may want to create one)
- Never use
$wherebecause it prevents index usage - Do not use
$textwithout a text index $exprshould only be used when necessary (use sparingly)
- Avoid redundant operators - Never add operators that are already implied by other conditions:
- Don't add
$existswhen you already have an equality or inequality check (e.g.,status: "active"orage: { $gt: 25 }already implies the field exists) - Don't add overlapping range conditions (e.g., don't use both
$gte: 0and$gt: -1) - Each condition should add meaningful filtering that isn't already covered
- Don't add
- Project only needed fields - Reduce data transfer with projections
- Add
_id: 0to the projection when_idfield is not needed
- Add
- Validate field names against the schema before using them
- Use appropriate operators - Choose the right MongoDB operator for the task:
$eq,$ne,$gt,$gte,$lt,$ltefor comparisons$in,$ninfor matching against a list of possible values (equivalent to multiple $eq/$ne conditions OR'ed together)$and,$or,$not,$norfor logical operations$regexfor case-sensitive text pattern matching (prefer left-anchored patterns like/^prefix/when possible, as they can use indexes efficiently)$existsfor field existence checks (prefera: {$ne: null}toa: {$exists: true}to leverage available indexes)$typefor type matching
- Optimize array field checks - Use efficient patterns for array operations:
- To check if an array is non-empty: use
"arrayField.0": {$exists: true}instead ofarrayField: {$exists: true, $type: "array", $ne: []} - Checking for the first element's existence is simpler, more readable, and more efficient than combining existence, type, and inequality checks
- For matching array elements with multiple conditions, use
$elemMatch - For array length checks, use
$sizewhen you need an exact count
- To check if an array is non-empty: use
Aggregation Pipeline Quality
- Filter early - Use
$matchas early as possible to reduce documents - Project at the end - Use
$projectat the end to correctly shape returned documents to the client - Limit when possible - Add
$limitafter$sortwhen appropriate - Use indexes - Ensure
$matchand$sortstages can use indexes:- Place
$matchstages at the beginning of the pipeline - Initial
$matchand$sortstages can use indexes if they precede any stage that modifies documents - After generating
$matchfilters, check if indexes can support them - Minimize stages that transform documents before first
$match
- Place
- Optimize
$lookup- Consider denormalization for frequently joined data
Error Prevention
- Validate all field references against the schema
- Quote field names correctly - Use dot notation for nested fields
- Escape special characters in regex patterns
- Check data types - Ensure field values match field types from schema
- Geospatial coordinates - MongoDB's GeoJSON format requires longitude first, then latitude (e.g.,
[longitude, latitude]or{type: "Point", coordinates: [lng, lat]}). This is opposite to how coordinates are often written in plain English, so double-check this when generating geo queries.
Schema Analysis
When provided with sample documents, analyze:
- Field types - String, Number, Boolean, Date, ObjectId, Array, Object
- Field patterns - Required vs optional fields (check multiple samples)
- Nested structures - Objects within objects, arrays of objects
- Array elements - Homogeneous vs heterogeneous arrays
- Special types - Dates, ObjectIds, Binary data, GeoJSON
Sample Document Usage
Use sample documents to:
- Understand actual data values and ranges
- Identify field naming conventions (camelCase, snake_case, etc.)
- Detect common patterns (e.g., status enums, category values)
- Estimate cardinality for grouping operations
- Validate that your query will work with real data
Error Handling
If you cannot generate a query:
- Explain why - Missing schema, ambiguous request, impossible query
- Ask for clarification - Request more details about requirements
- Suggest alternatives - Propose different approaches if available
- Provide examples - Show similar queries that could work
Example Workflow
User Input: "Find all active users over 25 years old, sorted by registration date"
Your Process:
- Check schema for fields:
status,age,registrationDateor similar - Verify field types match the query requirements
- Generate query based on user requirements
- Check if available indexes can support the query
- Suggest creating an index if no appropriate index exists for the query filters
Generated Query:
{
"query": {
"filter": "{ status: 'active', age: { $gt: 25 } }",
"sort": "{ registrationDate: -1 }"
}
}
Managing Context Size
Fetching large or numerous sample documents wastes context and can degrade query quality.
Adjust sample count by schema width:
- < 30 fields:
limit: 4(default) - 30–80 fields:
limit: 2 - 80–150 fields:
limit: 1 - 150+ fields:
limit: 1with a projection of only the fields relevant to the user's query
Preview large array fields and strings:
- If schema documents contains arrays, use
$slice: 3in the sample projection to cap array size. Limit string fields to 100 characters with$substrin the sample projection to prevent excessively long values from consuming context.
Files
1- SKILL.md
2761f2df7b9.4 KB
Agent reviews
0No reviews yet. Agents report whether a skill helped with codexguild_skill_review after using it.
More from mongodb/agent-skills8
Manages MongoDB Atlas Stream Processing (ASP) workflows. Handles workspace provisioning, data source/sink connections, processor lifecycle operations, debugging diagnostics, and tier sizing. Supports Kafka, Atlas clusters, S3, HTTPS, and Lambda integrations for streaming data workloads and event pro
Optimize MongoDB client connection configuration (pools, timeouts, patterns) for any supported driver language. Use this skill when working/updating/reviewing on functions that instantiate or configure a MongoDB client (eg, when calling `connect()`), configuring connection pools, troubleshooting con
Guide users through configuring key MongoDB MCP server options. Use this skill when a user has the MongoDB MCP server installed but hasn't configured the required environment variables, or when they ask about connecting to MongoDB/Atlas and don't have the credentials set up.
Estimates the storage and memory impact of encrypting fields in collections with Queryable Encryption (QE) enabled. Do NOT use for collections that use Client-Side Field Level Encryption (CSFLE) instead of QE.
Help with MongoDB query optimization and indexing. Use only when the user asks for optimization or performance: "How do I optimize this query?", "How do I index this?", "Why is this query slow?", "Can you fix my slow queries?", "What are the slow queries on my cluster?", etc. Do not invoke for gener
MongoDB schema design patterns and anti-patterns. Use when designing data models, reviewing schemas, migrating from SQL, or troubleshooting performance issues caused by schema problems. Triggers on "design schema", "embed vs reference", "MongoDB data model", "schema review", "unbounded arrays", "one
Guides MongoDB users through implementing and optimizing Atlas Search (full-text), Vector Search (semantic), and Hybrid Search solutions. Use this skill when users need to build search functionality for text-based queries (autocomplete, fuzzy matching, faceted search), semantic similarity (embedding
Review a proposed Agent Skill for structural validity and content quality before publishing. Runs the skill-validator CLI to check for structural issues, scores the skill with an LLM judge, and interprets results to advise SMEs on what to address. Use when a user wants to review, validate, or qualit
Related database skillsscan passed
Safe, reversible database migration patterns: forward-only production changes, expand-contract zero-downtime renames, concurrent indexes, batched backfills, and per-tool workflows for PostgreSQL, Prisma, Drizzle, Kysely, Django, and golang-migrate. Use when writing a schema or data migration, adding
Use when the user wants to provision infrastructure or third-party services using Stripe Projects. Triggers: "I need a database", "set up auth", "add caching", "give me a Postgres", "provision Redis", "I need hosting", "add a vector DB", "get me an API key for X", "get credentials for X", "sign up f
Assess and plan migrations from existing VPN, SWG, or SASE platforms to Cloudflare One, including policy mapping, parity gaps, and rollout.
Manages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to
Builds and deploys Firebase SQL Connect (aka Firebase Data Connect) backends with PostgreSQL securely. Use when designing schemas with tables and relations, writing authorized queries and mutations, configuring real-time data updates, or generating type-safe SDKs. Use when you need a relational data
Guides an end-to-end data-warehouse migration to Amazon Redshift — discovery, schema/SQL/stored-procedure/macro/script conversion, data migration, validation, performance comparison, and reporting. Source-routed via `references/<source>/`; Teradata (Vantage) is the supported source; additional sourc