MongoDB MCP Server

MongoDB MCP Server

一个模型上下文协议服务器,提供对 MongoDB 数据库的只读访问,使 AI 助手能够直接查询和分析 MongoDB 数据,同时保持数据安全。

数据库
JavaScript
访问服务器

Tools

list_databases

List all databases in the MongoDB server.

list_collections

List all collections in a database. Start here to understand what collections are available before querying.

get_schema

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 }

query

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

aggregate

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 - $lookup: Perform left outer joins - $unwind: Deconstruct array fields Unsafe/Blocked Stages: - $out: Write results to collection - $merge: Merge results into collection - $addFields: Add new fields - $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 }} ] }

get_collection_stats

Get detailed statistics about a collection. Returns information about: - Document count and size - Storage metrics - Index sizes and usage - Average document size - Padding factor

get_indexes

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

explain_query

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.

get_distinct_values

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 } }

sample_data

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

count_documents

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 } } }

find_by_ids

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 } }

geo_query

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: 1. 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" } 2. 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]] ] } }

text_search

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 }

README

MongoDB MCP 服务器

一个模型上下文协议服务器,通过标准化的 MCP 工具和资源提供对 MongoDB 数据库的只读访问。

<a href="https://glama.ai/mcp/servers/cmywezu1sn"> <img width="380" height="200" src="https://glama.ai/mcp/servers/cmywezu1sn/badge" alt="MongoDB Server MCP server" /> </a>

概述

此 MongoDB MCP 服务器使 AI 助手能够直接查询和分析 MongoDB 数据库,而无需写入权限,从而在提供强大的数据探索功能的同时保持数据安全。

功能

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 Code 文档

安全注意事项

  • 此服务器设计为提供只读访问
  • 连接字符串可能包含敏感的身份验证信息
  • 将连接字符串安全地存储在环境变量中
  • 使用具有只读权限的 MongoDB 用户

调试

由于 MCP 服务器通过 stdio 进行通信,因此调试可能具有挑战性。 使用 MCP Inspector,它作为包脚本提供:

npm run inspector

Inspector 将提供一个 URL 以访问浏览器中的调试工具。

推荐服务器

Claude Code MCP

Claude Code MCP

一个实现了 Claude Code 作为模型上下文协议(Model Context Protocol, MCP)服务器的方案,它可以通过标准化的 MCP 接口来使用 Claude 的软件工程能力(代码生成、编辑、审查和文件操作)。

精选
本地
JavaScript
Supabase MCP Server

Supabase MCP Server

一个模型上下文协议(MCP)服务器,它提供对 Supabase 管理 API 的编程访问。该服务器允许 AI 模型和其他客户端通过标准化的接口来管理 Supabase 项目和组织。

精选
JavaScript
@kazuph/mcp-gmail-gas

@kazuph/mcp-gmail-gas

用于 Gmail 集成的模型上下文协议 (Model Context Protocol, MCP) 服务器。它允许 Claude Desktop(或任何 MCP 客户端)通过 Google Apps Script 与您的 Gmail 帐户进行交互。

精选
JavaScript
MCP DuckDB Knowledge Graph Memory Server

MCP DuckDB Knowledge Graph Memory Server

一个为 Claude 设计的记忆服务器,它使用 DuckDB 存储和检索知识图谱数据,从而增强了对话的性能和查询能力,并能持久保存用户信息。

精选
TypeScript
Metabase MCP Server

Metabase MCP Server

使人工智能助手能够与 Metabase 数据库和仪表板进行交互,允许用户通过自然语言列出和执行查询、访问数据可视化以及与数据库资源进行交互。

精选
JavaScript
Linear MCP Server

Linear MCP Server

一个模型上下文协议(Model Context Protocol)服务器,它与 Linear 的问题跟踪系统集成,允许大型语言模型(LLM)通过自然语言交互来创建、更新、搜索和评论 Linear 问题。

精选
JavaScript
Airtable MCP Server

Airtable MCP Server

一个模型上下文协议(Model Context Protocol,MCP)服务器,通过 Claude Desktop 或其他 MCP 客户端,为以编程方式管理 Airtable 数据库、表格、字段和记录提供工具。

精选
JavaScript
mcp-shodan

mcp-shodan

用于查询 Shodan API 和 Shodan CVEDB 的 MCP 服务器。该服务器提供 IP 查询、设备搜索、DNS 查询、漏洞查询、CPE 查询等工具。

精选
JavaScript
Verodat MCP Server

Verodat MCP Server

一个 MCP 服务器,集成了 Verodat 的数据管理功能和像 Claude Desktop 这样的人工智能系统,使用户能够管理账户、工作区和数据集,并能对他们的数据执行人工智能驱动的查询。

官方
本地
TypeScript
Tembo MCP Server

Tembo MCP Server

一个 MCP 服务器,它使 Claude 能够与 Tembo Cloud 平台 API 交互,从而允许用户通过自然语言管理 Tembo Cloud 资源。

官方
TypeScript