MongoDB透镜
功能齐全的MCP服务器,用于MongoDB数据库分析。
MCP 服务配置
复制以下 JSON 到 OPClaw 或其他 MCP 客户端的配置文件中即可使用
{
"mcpServers": {
"mongodb-lens": {
"args": [
"run",
"--rm",
"-i",
"--network=host",
"mongodb-lens",
"mongodb://your-connection-string"
],
"command": "docker"
}
}
}
该服务需要配置环境变量:MONGODB_CONNECTION_STRING
服务介绍
MongoDB Lens
MongoDB Lens 是一个本地模型上下文协议 (MCP) 服务器,通过 LLMs 使用自然语言全面访问 MongoDB 数据库,以执行查询、运行聚合、优化性能等。
目录
快速开始
- 安装 MongoDB Lens
- 配置 MongoDB Lens
- 设置 您的 MCP 客户端(例如 Claude Desktop, Cursor 等)
- 使用 自然语言查询 探索您的 MongoDB 数据库
功能
工具
add-connection-alias: Add a new MongoDB connection aliasaggregate-data: Execute aggregation pipelinesanalyze-query-patterns: Analyze live queries and suggest optimizationsanalyze-schema: Automatically infer collection schemasbulk-operations: Perform multiple operations efficiently (requires confirmation for destructive operations)clear-cache: Clear memory caches to ensure fresh datacollation-query: Find documents with language-specific collation rulescompare-schemas: Compare schemas between two collectionsconnect-mongodb: Connect to a different MongoDB URIconnect-original: Connect back to the original MongoDB URI used at startupcount-documents: Count documents matching specified criteriacreate-collection: Create new collections with custom optionscreate-database: Create a new database with option to switch to itcreate-index: Create new indexes for performance optimizationcreate-timeseries: Create time series collections for temporal datacreate-user: Create new database users with specific rolescurrent-database: Show the current database contextdelete-document: Delete documents matching specified criteria (requires confirmation)distinct-values: Extract unique values for any fielddrop-collection: Remove collections from the database (requires confirmation)drop-database: Drop a database (requires confirmation)drop-index: Remove indexes from collections (requires confirmation)drop-user: Remove database users (requires confirmation)explain-query: Analyze query execution plansexport-data: Export query results in JSON or CSV formatfind-documents: Run queries with filters, projections, and sortinggenerate-schema-validator: Generate JSON Schema validatorsgeo-query: Perform geospatial queries with various operatorsget-stats: Retrieve database or collection statisticsgridfs-operation: Manage large files with GridFS bucketsinsert-document: Insert one or more documents into collectionslist-collections: Explore collections in the current databaselist-connections: View all available MongoDB connection aliaseslist-databases: View all accessible databasesrename-collection: Rename existing collections (requires confirmation when dropping targets)shard-status: View sharding configuration for databases and collectionstext-search: Perform full-text search across text-indexed fieldstransaction: Execute multiple operations in a single ACID transactionupdate-document: Update documents matching specified criteriause-database: Switch to a specific database contextvalidate-collection: Check for data inconsistencieswatch-changes: Monitor real-time changes to collections
资源
collection-indexes: 集合的索引信息collection-schema: 集合的模式信息collection-stats: 集合的性能统计collection-validation: 集合的验证规则collections: 当前数据库中的集合列表database-triggers: 数据库变更流和事件触发器配置database-users: 当前数据库中的数据库用户和角色databases: 所有可访问数据库的列表performance-metrics: 实时性能指标和分析数据replica-status: 副本集状态和配置server-status: 服务器状态信息stored-functions: 当前数据库中存储的 JavaScript 函数
提示
aggregation-builder: 逐步创建聚合管道backup-strategy: 定制备份和恢复建议data-modeling: 针对特定用例的 MongoDB 模式设计专家建议database-health-check: 全面的数据库健康评估和建议index-recommendation: 根据查询模式获取个性化的索引建议migration-guide: 逐步 MongoDB 版本迁移计划mongo-shell: 生成带有解释的 MongoDB shell 命令multi-tenant-design: 设计 MongoDB 多租户数据库架构query-builder: 交互式指导构建 MongoDB 查询query-optimizer: 对慢查询的优化建议schema-analysis: 详细的集合模式分析及建议schema-versioning: 管理 MongoDB 应用中的模式演进security-audit: 数据库安全分析及改进建议sql-to-mongodb: 将 SQL 查询转换为 MongoDB 聚合管道
其他功能
其他功能:概览
MongoDB Lens 包含许多其他功能:
- 配置文件: 通过
~/.mongodb-lens.[jsonc|json]自定义配置 - 环境变量覆盖: 通过
process.env.CONFIG_*覆盖配置设置 - 确认系统: 对破坏性操作进行两步验证
- 多连接: 定义并切换命名的 URI 别名
- 组件禁用: 选择性地禁用工具、提示或资源
- 连接韧性: 带有指数退避的自动重连
- 查询保护措施: 可配置的限制和性能保护
- 错误处理: 全面的 JSONRPC 错误代码和消息
- 模式推断: 通过智能采样进行高效的模式分析
- 凭证保护: 在日志中模糊处理连接字符串密码
- 内存管理: 对大型操作进行自动监控和清理
- 智能缓存: 为模式、索引、字段和集合优化缓存
- 向后兼容: 支持现代版和旧版 MongoDB
其他功能:新数据库元数据
MongoDB Lens 会在它创建的每个数据库中插入一个 metadata 集合。
这个 metadata 集合存储一个包含上下文信息的文档,作为数据库来源的永久记录,同时确保新的且为空的数据库在 MongoDB 的存储系统中持续存在。
{
"_id" : ObjectId("67d5284463788ec38aecee14"),
"created" : {
"timestamp" : ISODate("2025-03-15T07:12:04.705Z"),
"tool" : "MongoDB Lens v5.0.7",
"user" : "anonymous"
},
"mongodb" : {
"version" : "3.6.23",
"connectionInfo" : {
"host" : "unknown",
"readPreference" : "primary"
}
},
"database" : {
"name" : "example_database",
"description" : "Created via MongoDB Lens"
},
"system" : {
"hostname" : "unknown",
"platform" : "darwin",
"nodeVersion" : "v22.14.0"
},
"lens" : {
"version" : "5.0.7",
"startTimestamp" : ISODate("2025-03-15T07:10:06.084Z")
}
}
一旦你向新数据库添加了自己的集合,你可以通过 drop-collection 工具安全地移除 metadata 集合:
- "删除新数据库的 metadata 集合"
➥ 使用drop-collection工具(需要确认)
安装
MongoDB Lens 可以通过多种方式安装和运行:
安装:NPX
运行 MongoDB Lens 最简单的方法是使用 NPX。
首先,确保已安装 Node.js:
node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
然后,通过 NPX 运行 MongoDB Lens:
# Using default connection string mongodb://localhost:27017
npx -y mongodb-lens
# Using custom connection string
npx -y mongodb-lens mongodb://your-connection-string
# Using "@latest" to keep the package up-to-date
npx -y mongodb-lens@latest
[!TIP]
如果你在使用npx时遇到权限错误,可以尝试先运行npx clear-npx-cache,然后再运行npx -y mongodb-lens(这会清除缓存并重新下载包)。
安装:Docker Hub
[!NOTE]
Docker Hub 需要您在系统上安装并运行 Docker。
首先,确保已安装 Docker:
docker --version # Ideally >= v27.x
然后,通过 Docker Hub 运行 MongoDB Lens:
# Using default connection string mongodb://localhost:27017
docker run --rm -i --network=host furey/mongodb-lens
# Using custom connection string
docker run --rm -i --network=host furey/mongodb-lens mongodb://your-connection-string
# Using "--pull" to keep the Docker image up-to-date
docker run --rm -i --network=host --pull=always furey/mongodb-lens
安装:从源代码安装 Node.js
- 克隆 MongoDB Lens 仓库:
git clone https://github.com/furey/mongodb-lens.git - 导航到克隆的仓库目录:
cd /path/to/mongodb-lens - 确保已安装 Node.js:
node --version # 理想情况下 >= v22.x,但 MongoDB Lens 支持 >= v18.x - 安装 Node.js 依赖项:
npm ci - 启动服务器:
# 使用默认连接字符串 mongodb://localhost:27017 node mongodb-lens.js # 使用自定义连接字符串 node mongodb-lens.js mongodb://your-connection-string
安装:从源代码安装 Docker
[!NOTE]
从源代码安装 Docker 需要您在系统上安装并运行 Docker。
- 克隆 MongoDB Lens 仓库:
git clone https://github.com/furey/mongodb-lens.git - 导航到克隆的仓库目录:
cd /path/to/mongodb-lens - 确保已安装 Docker:
docker --version # 理想情况下 >= v27.x - 构建 Docker 镜像:
docker build -t mongodb-lens . - 运行容器:
# 使用默认连接字符串 mongodb://localhost:27017 docker run --rm -i --network=host mongodb-lens # 使用自定义连接字符串 docker run --rm -i --network=host mongodb-lens mongodb://your-connection-string
安装验证
为了验证安装,请将以下 JSONRPC 消息粘贴并运行到服务器的 stdio 中:
{"method":"resources/read","params":{"uri":"mongodb://databases"},"jsonrpc":"2.0","id":1}
服务器应该响应您的 MongoDB 实例中的数据库列表,例如:
{"result":{"contents":[{"uri":"mongodb://databases","text":"Databases (12):\n- admin (180.00 KB)\n- config (108.00 KB)\n- local (40.00 KB)\n- sample_airbnb (51.88 MB)\n- sample_analytics (9.46 MB)\n- sample_geospatial (980.00 KB)\n- sample_guides (40.00 KB)\n- sample_mflix (108.90 MB)\n- sample_restaurants (7.73 MB)\n- sample_supplies (968.00 KB)\n- sample_training (40.85 MB)\n- sample_weatherdata (2.69 MB)"}]},"jsonrpc":"2.0","id":1}
MongoDB Lens 现已安装完毕,并准备好接受 MCP 请求。
安装:旧版本的 MongoDB
如果连接到版本 < 4.0 的 MongoDB 实例,最新版本的 MongoDB Lens 所使用的 MongoDB Node.js 驱动程序将不兼容。具体来说,MongoDB Node.js 驱动程序版本 4.0.0 及以上需要 MongoDB 版本 4.0 或更高。
要使用旧版本的 MongoDB 实例运行 MongoDB Lens,您需要使用 3.x 系列的 MongoDB Node.js 驱动程序版本(例如 3.7.4 与 MongoDB 3.6 兼容)。
旧版本的 MongoDB:从源代码运行
- 克隆 MongoDB Lens 仓库:
git clone https://github.com/furey/mongodb-lens.git - 进入克隆的仓库目录:
cd /path/to/mongodb-lens - 修改
package.json:"dependencies": { ... - "mongodb": "^6.15.0", // 或者其他更新版本 + "mongodb": "^3.7.4", // 或者与你的旧版 MongoDB 实例兼容的 3.x 版本 ... } - 安装 Node.js 依赖项:
npm install - 启动 MongoDB Lens:
node mongodb-lens.js mongodb://older-mongodb-instance
这将使用与你的 MongoDB 实例兼容的旧版驱动程序。
[!NOTE]
你可能还需要回滚 这个提交 以添加useNewUrlParser和useUnifiedTopologyMongoDB 配置选项。
旧版 MongoDB:使用 NPX 或 Docker
如果你更喜欢使用 NPX 或 Docker,你需要使用一个带有兼容驱动程序的旧版 MongoDB Lens。
例如,MongoDB Lens 8.3.0 使用 MongoDB Node.js 驱动程序 3.7.4(见:package-lock.json)。
要使用 NPX 运行旧版 MongoDB Lens,请指定版本标签:
npx -y mongodb-lens@8.3.0
同样适用于 Docker:
docker run --rm -i --network=host furey/mongodb-lens:8.3.0
配置
配置:MongoDB 连接字符串
服务器接受 MongoDB 连接字符串作为其唯一参数。
示例 NPX 用法:
npx -y mongodb-lens@latest mongodb://your-connection-string
MongoDB 连接字符串具有以下格式:
mongodb://[username:password@]host[:port][/database][?options]
示例连接字符串:
- 本地连接:
mongodb://localhost:27017 - 连接到
mydatabase并从admin数据库中获取凭据:
mongodb://username:password@hostname:27017/mydatabase?authSource=admin - 连接到
mydatabase并包含各种其他选项:
mongodb://hostname:27017/mydatabase?retryWrites=true&w=majority
如果没有提供连接字符串,服务器将尝试通过本地连接进行连接。
配置:配置文件
MongoDB Lens 支持通过 JSON 配置文件进行广泛的自定义。
[!NOTE]
配置文件是可选的。如果没有提供配置文件,MongoDB Lens 将使用默认设置运行。
[!TIP]
你只需要在配置文件中包含你想自定义的设置。对于省略的值,MongoDB Lens 将使用默认设置。
[!TIP]
MongoDB Lens 支持.json和.jsonc(带注释的 JSON)配置文件格式。
{
"mongoUri": "mongodb://localhost:27017", // Default MongoDB connection string or object of alias-URI pairs
"connectionOptions": {
"maxPoolSize": 20, // Maximum number of connections in the pool
"retryWrites": false, // Whether to retry write operations
"connectTimeoutMS": 30000, // Connection timeout in milliseconds
"socketTimeoutMS": 360000, // Socket timeout in milliseconds
"heartbeatFrequencyMS": 10000, // How often to ping servers for status
"serverSelectionTimeoutMS": 30000 // Timeout for server selection
},
"defaultDbName": "admin", // Default database if not specified in URI
"connection": {
"maxRetries": 5, // Maximum number of initial connection attempts
"maxRetryDelayMs": 30000, // Maximum delay between retries
"reconnectionRetries": 10, // Maximum reconnection attempts if connection lost
"initialRetryDelayMs": 1000 // Initial delay between retries
},
"disabled": {
"tools": [], // Array of tools to disable or true to disable all
"prompts": [], // Array of prompts to disable or true to disable all
"resources": [] // Array of resources to disable or true to disable all
},
"enabled": {
"tools": true, // Array of tools to enable or true to enable all
"prompts": true, // Array of prompts to enable or true to enable all
"resources": true // Array of resources to enable or true to enable all
},
"cacheTTL": {
"stats": 15000, // Stats cache lifetime in milliseconds
"fields": 30000, // Fields cache lifetime in milliseconds
"schemas": 60000, // Schema cache lifetime in milliseconds
"indexes": 120000, // Index cache lifetime in milliseconds
"collections": 30000, // Collections list cache lifetime in milliseconds
"serverStatus": 20000 // Server status cache lifetime in milliseconds
},
"enabledCaches": [ // List of caches to enable
"stats", // Statistics cache
"fields", // Collection fields cache
"schemas", // Collection schemas cache
"indexes", // Collection indexes cache
"collections", // Database collections cache
"serverStatus" // MongoDB server status cache
],
"memory": {
"enableGC": true, // Whether to enable garbage collection
"warningThresholdMB": 1500, // Memory threshold for warnings
"criticalThresholdMB": 2000 // Memory threshold for cache clearing
},
"logLevel": "info", // Log level (info or verbose)
"disableDestructiveOperationTokens": false, // Whether to skip confirmation for destructive ops
"watchdogIntervalMs": 30000, // Interval for connection monitoring
"defaults": {
"slowMs": 100, // Threshold for slow query detection
"queryLimit": 10, // Default limit for query results
"allowDiskUse": true, // Allow operations to use disk for large datasets
"schemaSampleSize": 100, // Sample size for schema inference
"aggregationBatchSize": 50 // Batch size for aggregation operations
},
"security": {
"tokenLength": 4, // Length of confirmation tokens
"tokenExpirationMinutes": 5, // Expiration time for tokens
"strictDatabaseNameValidation": true // Enforce strict database name validation
},
"tools": {
"transaction": {
"readConcern": "snapshot", // Read concern level for transactions
"writeConcern": {
"w": "majority" // Write concern for transactions
}
},
"bulkOperations": {
"ordered": true // Whether bulk operations execute in order
},
"export": {
"defaultLimit": -1, // Default limit for exports (-1 = no limit)
"defaultFormat": "json" // Default export format (json or csv)
},
"watchChanges": {
"maxDurationSeconds": 60, // Maximum duration for change streams
"defaultDurationSeconds": 10 // Default duration for change streams
},
"queryAnalysis": {
"defaultDurationSeconds": 10 // Default duration for query analysis
}
}
}
默认情况下,MongoDB Lens 会在以下位置查找配置文件:
- 首先查找
~/.mongodb-lens.jsonc,如果不存在,则回退到 ~/.mongodb-lens.json
要自定义配置文件路径,请将环境变量 CONFIG_PATH 设置为你希望的文件路径。
NPX 使用示例:
CONFIG_PATH='/path/to/config.json' npx -y mongodb-lens@latest
Docker Hub 使用示例:
docker run --rm -i --network=host --pull=always -v /path/to/config.json:/root/.mongodb-lens.json furey/mongodb-lens
配置:配置文件生成
你可以使用 config:create 脚本自动生成配置文件:
# NPX Usage (recommended)
npx -y mongodb-lens@latest config:create
# Node.js Usage
npm run config:create
# Force overwrite existing files
npx -y mongodb-lens@latest config:create -- --force
npm run config:create -- --force
该脚本提取上面的示例配置文件并将其保存到 ~/.mongodb-lens.jsonc
配置文件生成:自定义路径
你可以使用 CONFIG_PATH 环境变量指定自定义输出位置。
- 如果
CONFIG_PATH没有文件扩展名,则被视为目录并