Mongodb Natural Language Querying
MongoDBOfficialPublished by MongoDB
- Skill
- Tool integration
- Data and AI
- Apache-2.0
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill acts as an expert assistant for interacting with MongoDB databases. It leverages MCP tools to inspect collection schemas, indexes, and sample documents to ensure generated queries are accurate, performant, and syntactically correct. It focuses on read-only operations, providing either standard find queries or complex aggregation pipelines based on user requirements.
What it does
- Translates natural language requests into MongoDB find queries or aggregation pipelines.
- Automatically fetches and validates collection schemas and indexes before query generation.
- Analyzes sample documents to understand data patterns and field types.
- Provides optimized query structures while avoiding anti-patterns like $where.
- Supports complex operations including grouping, joins, and array manipulations.
- Offers guidance on index usage and query performance.
When to use it
- When you need to write or generate MongoDB queries from natural language descriptions.
- When you are unsure of the correct MongoDB query syntax for a specific filtering task.
- When you need to perform data aggregation or grouping in a MongoDB collection.
- When you want to translate SQL-like logic into MongoDB query syntax.
- When you need to verify if your query requirements align with existing collection schemas.
Advantages
- Reduces syntax errors by validating field names against the actual database schema.
- Promotes performance by suggesting index-friendly query patterns.
- Simplifies complex aggregation logic through automated pipeline construction.
- Ensures context-aware generation by analyzing real data samples.
- Prevents common pitfalls by adhering to MongoDB best practices.
Usage examples
- “Find all active users over 25 years old, sorted by registration date.”
- The agent inspects the schema for 'status', 'age', and 'registrationDate', then returns a JSON-formatted find query with the appropriate filter and sort parameters.
- “How do I calculate the total amount per category for active orders?”
- The agent generates an aggregation pipeline using $match to filter for 'active' status and $group to sum the 'amount' field by 'category'.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/mongodb/mongodb-natural-language-querying/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip mongodb-natural-language-querying.zip -d .agents/skills
Documentation by MongoDB
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 usageDo 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
Project only needed fields - Reduce data transfer with projections
Add
_id: 0to the projection when_idfield is not needed
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
$elemMatchFor array length checks, use
$sizewhen you need an exact count
Aggregation Pipeline Quality
Filter early - Use
$matchas early as possible to reduce documentsProject at the end - Use
$projectat the end to correctly shape returned documents to the clientLimit when possible - Add
$limitafter$sortwhen appropriateUse indexes - Ensure
$matchand$sortstages can use indexes:Place
$matchstages at the beginning of the pipelineInitial
$matchand$sortstages can use indexes if they precede any stage that modifies documentsAfter generating
$matchfilters, check if indexes can support themMinimize stages that transform documents before first
$match
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 similarVerify 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: 280–150 fields:
limit: 1150+ 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
- ATTRIBUTION.mdAdded by AutoGineer869 B
- LICENSELicence file added by AutoGineer11.1 KiB
- SKILL.md9.4 KiB
LICENSE
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Requirements and compatibility
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: Declares allowed tools, Needs an MCP server
Security
No issues found by our static scan· No issues found
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-natural-language-querying · 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-natural-language-querying.zip