MongoDB MCP Server
MongoDB MCP 服务器
模型上下文协议服务器,通过标准化的 MCP 工具和资源提供对 MongoDB 数据库的只读访问。
概述
该 MongoDB MCP 服务器使 AI 助手能够直接查询和分析 MongoDB 数据库,而无需写入权限,在提供强大的数据探索功能的同时保证数据安全。
Related MCP server: MongoDB MCP Server for LLMs
特征
MongoDB 操作
数据库探索:列出数据库和集合
模式发现:从样本文档推断集合模式
查询:使用过滤、投影、排序和限制执行 MongoDB 查询
聚合:运行带有安全验证的只读聚合管道
文本搜索:使用文本索引对集合进行全文搜索
地理空间查询:查找点附近、多边形内或相交几何体的位置
文档操作:计数文档、随机抽样文档、通过 ID 查找文档
数据分析:获取集合统计信息、索引信息和查询执行计划
性能洞察:检查查询执行计划以优化性能
数据探索:获取不同的值、字段分布和数据样本
格式转换:将查询结果导出为 JSON 或 CSV 格式
增强功能
模式推断:自动从文档中检测数据类型和结构
可视化提示:根据结果内容进行数据可视化的智能建议
安全验证:防止聚合管道中的写入操作
示例丰富的文档:每个工具在其描述中包含详细的示例
要求
环境变量
MONGODB_URI(必需):如果需要,带有身份验证的 MongoDB 连接字符串MONGODB_DEFAULT_DATABASE(可选):查询中未指定时的默认数据库名称
先决条件
通过网络访问 MongoDB 服务器
如果 MongoDB 实例需要,则需要身份验证凭据
对目标数据库的适当读取权限
安装
从源代码构建
安装依赖项:
npm install构建服务器:
npm run build对于使用自动重建的开发:
npm run watch与 Claude Desktop 集成
要与 Claude Desktop 一起使用,请添加服务器配置:
在 MacOS 上: ~/Library/Application Support/Claude/claude_desktop_config.json在 Windows 上: %APPDATA%/Claude/claude_desktop_config.json
{
"mcpServers": {
"mongodb": {
"command": "/path/to/mongodb-server/build/index.js",
"env": {
"MONGODB_URI": "mongodb://username:password@hostname:port/database",
"MONGODB_DEFAULT_DATABASE": "your_default_db"
}
}
}
}与 Claude Web 集成
对于通过 MCP Chrome 扩展程序访问 Claude Web,将配置添加到 Cline MCP 设置:
{
"mcpServers": {
"mongodb": {
"command": "node",
"args": ["/path/to/mongodb-server/build/index.js"],
"env": {
"MONGODB_URI": "mongodb://username:password@hostname:port/database",
"MONGODB_DEFAULT_DATABASE": "your_default_db"
}
}
}
}与 Claude Code 集成
要与 Claude Code 一起使用,请使用以下命令:
cd /path/to/my/project
claude mcp add mongo-server /path/to/mongodb-mcp/build/index.js -e "MONGODB_URI=mongodb://user@password:27017/dbname?authSource=authDbName" -e MONGO_DEFAULT_DATABASE=dbname 确保用实际的 MongoDB 连接字符串和默认数据库名称替换占位符。
如果配置正确,运行claude时你应该会看到以下内容:
╭───────────────────────────────────────────────────────╮
│ ✻ Welcome to Claude Code research preview! │
│ │
│ /help for help │
│ │
│ cwd: <path-to-project-directory> │
│ │
│ ─────────────────────────────────────────────────── │
│ │
│ MCP Servers: │
│ │
│ • mongo-server connected │
╰───────────────────────────────────────────────────────╯
如果遇到问题,请参阅 Claude 代码文档。
安全注意事项
该服务器设计提供只读访问权限
连接字符串可能包含敏感的身份验证信息
将连接字符串安全地存储在环境变量中
使用具有只读权限的 MongoDB 用户
调试
由于 MCP 服务器通过 stdio 进行通信,调试起来可能比较困难。您可以使用MCP Inspector 工具,它包含在包脚本中:
npm run inspector检查器将提供一个 URL 来访问浏览器中的调试工具。
Available Tools
14 toolsaggregateA
Execute a read-only aggregation pipeline on a collection.
Supported Stages:
$match: Filter documents
$group: Group documents by a key
$sort: Sort documents
$project: Shape the output
$addFields - Include additional or calculated fields
$lookup: Perform left outer joins
$unwind: Deconstruct array fields
Unsafe/Blocked Stages:
$out: Write results to collection
$merge: Merge results into collection
$set: Set field values
$unset: Remove fields
$replaceRoot: Replace document structure
$replaceWith: Replace document
Example - User Statistics by Role: use_mcp_tool with server_name: "mongodb", tool_name: "aggregate", arguments: { "collection": "users", "pipeline": [ { "$match": { "active": true } }, { "$group": { "_id": "$role", "count": { "$sum": 1 }, "avgAge": { "$avg": "$age" } }}, { "$sort": { "count": -1 } } ], "limit": 100 }
Example - Posts with Author Details: use_mcp_tool with server_name: "mongodb", tool_name: "aggregate", arguments: { "collection": "posts", "pipeline": [ { "$match": { "published": true } }, { "$lookup": { "from": "users", "localField": "authorId", "foreignField": "_id", "as": "author" }}, { "$unwind": "$author" }, { "$project": { "title": 1, "authorName": "$author.name", "publishDate": 1 }} ] }
Inputs: collection (required), pipeline (required), database, limit.
count_documentsA
Count documents in a collection that match a filter.
Benefits:
More efficient than retrieving full documents
Good for understanding data volume
Can help planning query strategies
Optimize pagination implementation
Example: use_mcp_tool with server_name: "mongodb", tool_name: "count_documents", arguments: { "collection": "users", "filter": { "active": true, "age": { "$gte": 21 } } }
Inputs: collection (required), database, filter.
explain_queryA
Get the execution plan for a query.
Helps understand:
How MongoDB will execute the query
Which indexes will be used
Number of documents examined
Execution stages and timing
Use this to optimize slow queries.
Inputs: collection (required), filter (required), database, projection, +1 more.
find_by_idsA
Find multiple documents by their IDs in a single request.
Advantages:
More efficient than multiple single document lookups
Preserves ID order in results when possible
Can filter specific fields with projection
Handles both string and ObjectId identifiers
Example: use_mcp_tool with server_name: "mongodb", tool_name: "find_by_ids", arguments: { "collection": "products", "ids": ["5f8d0f3c", "5f8d0f3d", "5f8d0f3e"], "idField": "_id", "projection": { "name": 1, "price": 1 } }
Inputs: collection (required), ids (required), database, idField, +1 more.
geo_queryA
Execute geospatial queries on a MongoDB collection.
Supports:
Finding points near a location
Finding documents within a polygon, circle, or box
Calculating distances between points
GeoJSON and legacy coordinate pair formats
Requirements:
Collection must have a geospatial index (2dsphere recommended)
Coordinates should follow MongoDB conventions (longitude first, then latitude)
Examples:
Find locations near a point (2 miles radius): use_mcp_tool with server_name: "mongodb", tool_name: "geo_query", arguments: { "collection": "restaurants", "operation": "near", "point": [-73.9667, 40.78], "maxDistance": 3218.69, // 2 miles in meters "distanceField": "distance" }
Find locations within a polygon: use_mcp_tool with server_name: "mongodb", tool_name: "geo_query", arguments: { "collection": "properties", "operation": "geoWithin", "geometry": { "type": "Polygon", "coordinates": [ [[-73.958, 40.8], [-73.94, 40.79], [-73.95, 40.76], [-73.97, 40.76], [-73.958, 40.8]] ] } }
Inputs: collection (required), operation (required), database, locationField, +8 more.
get_collection_statsC
Get detailed statistics about a collection.
Returns information about:
Document count and size
Storage metrics
Index sizes and usage
Average document size
Padding factor
Inputs: collection (required), database.
get_distinct_valuesA
Get distinct values for a field in a collection.
Useful for:
Understanding data distribution
Finding unique categories
Data quality checks
Identifying outliers
Example: use_mcp_tool with server_name: "mongodb", tool_name: "get_distinct_values", arguments: { "collection": "users", "field": "role", "filter": { "active": true } }
Inputs: collection (required), field (required), database, filter.
get_indexesB
Get information about indexes on a collection.
Returns details about:
Index names and fields
Index types (single field, compound, text, etc.)
Index sizes
Index options
Usage statistics
Inputs: collection (required), database.
get_schemaA
Infer schema from a collection by analyzing sample documents.
Best Practice: Use this before querying to understand collection structure.
Example: use_mcp_tool with server_name: "mongodb", tool_name: "get_schema", arguments: { "collection": "users", "sampleSize": 100 }
Inputs: collection (required), database, sampleSize.
list_collectionsA
List all collections in a database.
Start here to understand what collections are available before querying.
Inputs: database.
list_databasesB
List all databases in the MongoDB server.
Inputs: no named parameters.
queryA
Execute a read-only query on a collection using MongoDB query syntax.
Supports both JSON and CSV output formats:
Use outputFormat="json" for standard JSON (default)
Use outputFormat="csv" for comma-separated values export
Best Practices:
Use projections to fetch only needed fields
Add limits for large collections
Use sort for consistent ordering
Example - Standard Query: use_mcp_tool with server_name: "mongodb", tool_name: "query", arguments: { "collection": "users", "filter": { "age": { "$gte": 21 } }, "projection": { "name": 1, "email": 1 }, "sort": { "name": 1 }, "limit": 100 }
Example - CSV Export: use_mcp_tool with server_name: "mongodb", tool_name: "query", arguments: { "collection": "users", "filter": { "active": true }, "outputFormat": "csv", "formatOptions": { "includeHeaders": true, "delimiter": "," } }
Inputs: collection (required), filter (required), database, projection, +4 more.
sample_dataA
Get a random sample of documents from a collection.
Supports both JSON and CSV output formats:
Use outputFormat="json" for standard JSON (default)
Use outputFormat="csv" for comma-separated values export
Useful for:
Exploratory data analysis
Testing with representative data
Understanding data distribution
Performance testing with realistic data subsets
Example - JSON Sample: use_mcp_tool with server_name: "mongodb", tool_name: "sample_data", arguments: { "collection": "users", "size": 50 }
Example - CSV Export: use_mcp_tool with server_name: "mongodb", tool_name: "sample_data", arguments: { "collection": "users", "size": 100, "outputFormat": "csv", "formatOptions": { "includeHeaders": true, "delimiter": "," } }
Inputs: collection (required), database, size, outputFormat, +1 more.
text_searchB
Perform a full-text search on a collection.
Requirements:
Collection must have a text index
Only one text index per collection is allowed
Features:
Supports phrases and keywords
Word stemming
Stop words removal
Text score ranking
Example: use_mcp_tool with server_name: "mongodb", tool_name: "text_search", arguments: { "collection": "articles", "searchText": "mongodb database", "filter": { "published": true }, "limit": 10, "includeScore": true }
Inputs: collection (required), searchText (required), database, filter, +2 more.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 14 tools
Most tools have distinct purposes, such as aggregate for complex pipelines, query for basic queries, and geo_query for spatial operations. However, query and sample_data both retrieve documents with overlapping functionality, and get_schema might be confused with get_collection_stats for understanding collection structure, leading to some potential confusion.
The naming follows a consistent verb_noun pattern throughout, like count_documents, explain_query, and get_indexes. There are minor deviations with list_collections and list_databases using 'list' instead of 'get', but overall the pattern is clear and predictable.
With 14 tools, this is well-scoped for a MongoDB server, covering a comprehensive range of read-only operations from basic queries to advanced analytics. Each tool serves a specific purpose, such as aggregation, indexing, geospatial queries, and schema analysis, without feeling bloated or incomplete.
The tool set provides complete coverage for read-only MongoDB operations, including querying, aggregation, indexing, geospatial queries, text search, and metadata inspection. There are no obvious gaps; it supports everything from data retrieval to performance optimization and schema exploration for the domain.
Maintenance
Related MCP Connectors
The HubSpot MCP Server acts as a bridge that enables AI assistants and Large Language Models to securely interact with HubSpot CRM data through natural conversation, without requiring users to understand complex API structures. It provides read-only access to standard CRM objects (contacts, companies, deals, tickets, products, invoices, and more) and their associations, secured via OAuth 2.0, allowing AI agents to perform tasks like summarizing deals, fetching company updates, and looking up record changes.
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
The BigQuery remote MCP server is a fully managed service that uses the Model Context Protocol to connect AI applications and LLMs to BigQuery data sources. It provides secure, standardized tools for AI agents to list datasets and tables, retrieve schemas, generate and execute SQL queries through natural language, and analyze data—enabling direct access to enterprise analytics data without requiring manual SQL coding.
Draxlr's remote MCP server connects AI assistants to your SQL databases and dashboards. Explore schemas, run read-only queries, manage saved queries and dashboards, and export results, all with row-level security so each user sees only their own data.
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables LLMs to interact directly with MongoDB databases, allowing users to query collections, inspect schemas, and manage data through natural language.1MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server that enables LLMs to interact directly with MongoDB databases, allowing users to query collections, inspect schemas, and manage data through natural language.MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol (MCP) server for MongoDB operations, enabling AI assistants to interact with MongoDB databases through a standardized interface.6MIT
- FlicenseNot gradedqualityDmaintenanceA read-only MongoDB MCP server designed for serverless deployment on Vercel, providing secure, limited access to MongoDB databases for AI assistants.1-