Skip to main content
Glama

MongoDB Lens

MongoDB 镜头

MongoDB Lens是一个本地模型上下文协议 (MCP) 服务器,具有通过 LLM 使用自然语言对 MongoDB 数据库进行全功能访问的功能,可以执行查询、运行聚合、优化性能等。

内容

快速入门

特征

工具

资源

提示

其他功能

其他功能:概述

MongoDB Lens 还包含许多其他功能:

  • 配置文件:通过~/.mongodb-lens.[jsonc|json]进行自定义配置
  • Env Var Overrides :通过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集合:

  • “删除新数据库的元数据集合” ➥使用drop-collection工具(带确认)

安装

MongoDB Lens 可以通过多种方式安装和运行:

安装:NPX

[!NOTE] NPX 需要在你的系统上安装并运行Node.js (建议:使用Volta )。

运行 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 -y mongodb-lens之前运行npx clear-npx-cache (这将清除缓存并重新下载包)。

安装: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

[!NOTE] 源代码中的 Node.js 需要在你的系统上安装并运行Node.js (建议:使用Volta )。

  1. 克隆 MongoDB Lens 存储库:
    git clone https://github.com/furey/mongodb-lens.git
  2. 导航到克隆的存储库目录:
    cd /path/to/mongodb-lens
  3. 确保已安装 Node.js:
    node --version # Ideally >= v22.x but MongoDB Lens is >= v18.x compatible
  4. 安装 Node.js 依赖项:
    npm ci
  5. 启动服务器:
    # Using default connection string mongodb://localhost:27017 node mongodb-lens.js # Using custom connection string node mongodb-lens.js mongodb://your-connection-string

安装:从源代码安装 Docker

[!NOTE] 从源代码运行 Docker 需要在你的系统上安装并运行Docker

  1. 克隆 MongoDB Lens 存储库:
    git clone https://github.com/furey/mongodb-lens.git
  2. 导航到克隆的存储库目录:
    cd /path/to/mongodb-lens
  3. 确保已安装 Docker:
    docker --version # Ideally >= v27.x
  4. 构建 Docker 镜像:
    docker build -t mongodb-lens .
  5. 运行容器:
    # Using default connection string mongodb://localhost:27017 docker run --rm -i --network=host mongodb-lens # Using custom connection string 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 Lens 与较旧的 MongoDB 实例一起使用,您需要使用3.x系列的 MongoDB Node.js 驱动程序版本(例如与 MongoDB 3.6兼容的3.7.4 )。

旧 MongoDB 版本:从源代码运行
  1. 克隆 MongoDB Lens 存储库:
    git clone https://github.com/furey/mongodb-lens.git
  2. 导航到克隆的存储库目录:
    cd /path/to/mongodb-lens
  3. 修改package.json
    "dependencies": { ... - "mongodb": "^6.15.0", // Or whatever newer version is listed + "mongodb": "^3.7.4", // Or whatever 3.x version is compatible with your older MongoDB instance ... }
  4. 安装 Node.js 依赖项:
    npm install
  5. 启动 MongoDB Lens:
    node mongodb-lens.js mongodb://older-mongodb-instance

这将使用与您的 MongoDB 实例兼容的旧驱动程序版本。

[!NOTE] 您可能还需要撤消此提交以重新添加useNewUrlParseruseUnifiedTopology MongoDB 配置选项。

较旧的 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
  • 使用来自admin数据库的凭据连接到mydatabasemongodb://username:password@hostname:27017/mydatabase?authSource=admin
  • 使用其他各种选项连接到mydatabasemongodb://hostname:27017/mydatabase?retryWrites=true&w=majority

如果没有提供连接字符串,服务器将尝试通过本地连接进行连接。

配置:配置文件

MongoDB Lens 支持通过 JSON 配置文件进行广泛的自定义。

配置文件是可选的。如果未提供配置文件,MongoDB Lens 将使用默认设置运行。

您只需在配置文件中包含要自定义的设置即可。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没有文件扩展名,则将其视为目录并附加.mongodb-lens.jsonc
  • 如果CONFIG_PATH.json (而不是.jsonc )结尾,则生成的文件中删除注释

NPX 使用示例:

# With custom path CONFIG_PATH=/path/to/config.jsonc npx -y mongodb-lens@latest config:create # Save to directory (will append .mongodb-lens.jsonc to the path) CONFIG_PATH=/path/to/directory npx -y mongodb-lens@latest config:create # Save as JSON instead of JSONC CONFIG_PATH=/path/to/config.json npx -y mongodb-lens@latest config:create

Node.js 使用示例:

# With custom path CONFIG_PATH=/path/to/config.jsonc node mongodb-lens.js config:create # Save to directory (will append .mongodb-lens.jsonc to the path) CONFIG_PATH=/path/to/directory node mongodb-lens.js config:create # Save as JSON instead of JSONC CONFIG_PATH=/path/to/config.json node mongodb-lens.js config:create

配置:多个 MongoDB 连接

MongoDB Lens 支持配置文件中带有别名的多个 MongoDB URI,允许您使用简单名称在不同的 MongoDB 实例之间轻松切换。

要配置多个连接,请将mongoUri配置设置设置为具有别名-URI 对的对象:

{ "mongoUri": { "main": "mongodb://localhost:27017", "backup": "mongodb://localhost:27018", "atlas": "mongodb+srv://username:password@cluster.mongodb.net/mydb" } }

使用以下配置:

  • 列表中的第一个 URI(例如main )在启动时成为默认连接
  • 您可以使用自然语言切换连接: "Connect to backup""Connect to atlas"
  • 原始语法仍然有效: "Connect to mongodb://localhost:27018"
  • list-connections工具显示所有可用的连接别名

[!NOTE] 使用命令行参数指定连接时,您可以使用完整的 MongoDB URI 或配置文件中定义的别名。

[!TIP] 要在运行时添加连接别名,请使用add-connection-alias工具。

配置:环境变量覆盖

MongoDB Lens 支持配置设置的环境变量覆盖。

环境变量优先于配置文件设置。

配置环境变量遵循命名模式:

CONFIG_[SETTING PATH, SNAKE CASED, UPPERCASED]

覆盖示例:

配置设置环境变量覆盖
mongoUriCONFIG_MONGO_URI
logLevelCONFIG_LOG_LEVEL
defaultDbNameCONFIG_DEFAULT_DB_NAME
defaults.queryLimitCONFIG_DEFAULTS_QUERY_LIMIT
tools.export.defaultFormatCONFIG_TOOLS_EXPORT_DEFAULT_FORMAT
connectionOptions.maxPoolSizeCONFIG_CONNECTION_OPTIONS_MAX_POOL_SIZE
connection.reconnectionRetriesCONFIG_CONNECTION_RECONNECTION_RETRIES

对于环境变量值:

  • 对于布尔设置,使用字符串值'true''false'
  • 对于数字设置,请使用字符串表示形式。
  • 对于嵌套对象或数组,请使用 JSON 字符串。

NPX 使用示例:

CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest

Docker Hub 使用示例:

docker run --rm -i --network=host --pull=always -e CONFIG_DEFAULTS_QUERY_LIMIT='25' furey/mongodb-lens

配置:跨平台环境变量

为了在 Windows、macOS 和 Linux 上一致地使用环境变量,请考虑使用cross-env

  1. 全局安装跨环境:
    # Using NPM npm install -g cross-env # Using Volta (see: https://volta.sh) volta install cross-env
  2. 在本文档的示例中,为任何 NPX 或 Node.js 环境变量添加前缀:
    # Example NPX usage with cross-env cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' npx -y mongodb-lens@latest # Example Node.js usage with cross-env cross-env CONFIG_DEFAULTS_QUERY_LIMIT='25' node mongodb-lens.js

客户端设置

客户端设置:Claude Desktop

要将 MongoDB Lens 与 Claude Desktop 一起使用:

  1. 安装Claude Desktop
  2. 打开claude_desktop_config.json (如果不存在则创建):
    • macOS: ~/Library/Application Support/Claude/claude_desktop_config.json
    • Windows: %APPDATA%\Claude\claude_desktop_config.json
  3. 根据配置选项添加 MongoDB Lens 服务器配置
  4. 重启Claude桌面
  5. 与 Claude 开始讨论您的 MongoDB 数据
Claude 桌面配置选项

对于每个选项:

  • mongodb://your-connection-string替换为您的 MongoDB 连接字符串,或者省略它以使用默认的mongodb://localhost:27017
  • 要使用自定义配置文件,请设置CONFIG_PATH环境变量。
  • 要包含环境变量:
    • 对于 NPX 或 Node.js,添加带有键值对的"env": {} ,例如:
      "command": "/path/to/npx", "args": [ "-y", "mongodb-lens@latest", "mongodb://your-connection-string" ], "env": { "CONFIG_LOG_LEVEL": "verbose" }
    • 对于 Docker 添加-e标志,例如:
      "command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "--pull=always", "-e", "CONFIG_LOG_LEVEL=verbose", "furey/mongodb-lens", "mongodb://your-connection-string" ]
选项 1:NPX(推荐)
{ "mcpServers": { "mongodb-lens": { "command": "/path/to/npx", "args": [ "-y", "mongodb-lens@latest", "mongodb://your-connection-string" ] } } }
选项 2:Docker Hub 镜像
{ "mcpServers": { "mongodb-lens": { "command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "--pull=always", "furey/mongodb-lens", "mongodb://your-connection-string" ] } } }
选项 3:本地 Node.js 安装
{ "mcpServers": { "mongodb-lens": { "command": "/path/to/node", "args": [ "/path/to/mongodb-lens.js", "mongodb://your-connection-string" ] } } }
选项 4:本地 Docker 镜像
{ "mcpServers": { "mongodb-lens": { "command": "docker", "args": [ "run", "--rm", "-i", "--network=host", "mongodb-lens", "mongodb://your-connection-string" ] } } }

客户端设置:MCP 检查器

MCP Inspector是一款用于测试和调试 MCP 服务器的工具。

[!NOTE] MCP Inspector 在端口 3000 上启动代理服务器,在端口 5173 上启动 Web 客户端。

NPX 使用示例:

  1. 运行 MCP 检查器:
    # Using default connection string mongodb://localhost:27017 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest # Using custom connection string npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string # Using custom ports SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
  2. 打开 MCP 检查器: http://localhost:5173

MCP Inspector 应该支持 MongoDB Lens 的全部功能,包括集合名称和查询字段的自动完成。

更多信息请参见: MCP 检查器

客户端设置:其他 MCP 客户端

MongoDB Lens 应该可以与任何与 MCP 兼容的客户端一起使用。

更多信息,请参阅: MCP 文档:示例客户端

数据保护

为了在使用 MongoDB Lens 时保护您的数据,请考虑以下事项:

数据保护:只读用户帐户

将 MongoDB Lens 连接到数据库时,MongoDB 连接字符串中授予用户的权限决定了可以执行的操作。当用例合适时,只读用户可以防止意外的写入或删除,确保 MongoDB Lens 可以查询数据但不能更改数据。

要进行此设置,请创建一个具有read角色的用户,该角色的作用域是目标数据库。在 MongoDB shell 中,您可以运行以下命令:

use admin db.createUser({ user: 'readonly', pwd: 'eXaMpLePaSsWoRd', roles: [{ role: 'read', db: 'mydatabase' }] })

然后,将这些凭据应用到您的 MongoDB 连接字符串:

mongodb://readonly:eXaMpLePaSsWoRd@localhost:27017/mydatabase

使用只读凭据是一种简单而有效的强制安全边界的方法,特别是当您探究模式或运行临时查询时。

数据保护:使用数据库备份

使用 MongoDB Lens 时,请考虑连接到托管在单独的 MongoDB 实例上的数据的备份副本。

首先使用mongodump生成备份。接下来,启动一个新的 MongoDB 实例(例如,在27018等其他端口上),并使用mongorestore在该实例上还原备份。运行后,将 MongoDB Lens 指向备份实例的连接字符串(例如mongodb://localhost:27018/mydatabase )。

这种方法为您提供了一个沙箱来测试复杂或破坏性的操作,而不会冒意外损坏实时数据的风险。

数据保护:数据流注意事项

数据流考虑:数据如何在系统中流动

当使用带有远程 LLM 提供商(例如通过 Claude Desktop 的 Anthropic)的 MCP 服务器时,了解数据如何在系统中流动是保护敏感信息免遭意外泄露的关键。

当您通过 MCP 客户端发送 MongoDB 相关查询时,会发生以下情况:

[!NOTE] 虽然此示例使用本地 MongoDB 实例,但相同的原则也适用于远程 MongoDB 实例。

  1. 您提交请求➥例如“显示所有 30 岁以上的用户”
  2. 您的客户将请求发送到远程 LLM➥ LLM 提供商会收到您的确切措辞以及可用的 MCP 工具及其参数的列表。
  3. 远程 LLM 解释您的请求➥ 它确定您的意图并指示客户端使用具有适当参数的特定 MCP 工具。
  4. 客户端要求 MongoDB Lens 运行该工具➥ 这通过 stdio 在您的机器上本地进行。
  5. MongoDB Lens 查询您的 MongoDB 数据库
  6. MongoDB Lens 检索您的 MongoDB 查询结果
  7. MongoDB Lens 将数据发送回客户端➥ 客户端接收由 MongoDB Lens 格式化的结果。
  8. 客户端将数据转发到远程 LLM➥ LLM 提供程序可以看到 MongoDB Lens 返回的精确数据。
  9. 远程 LLM 处理数据➥它可能会进一步总结或格式化结果。
  10. 远程LLM将最终回复发送给客户端➥客户端向您显示答案。

远程 LLM 提供商会同时看到您的原始请求和来自 MongoDB Lens 的完整响应。如果您的数据库包含敏感字段(例如密码、个人信息等),除非您采取预防措施,否则这些数据可能会被无意中传输给远程提供商。

数据流注意事项:使用投影保护敏感数据

为了防止敏感数据被发送到远程 LLM 提供商,请在使用find-documentsaggregate-dataexport-data等工具时使用投影的概念。投影允许您指定在查询结果中包含或排除哪些字段,从而确保敏感信息保留在本地。

投影用法示例:

  • “显示所有超过 30 岁的用户,但使用投影隐藏他们的密码。” ➥ 使用带有投影的find-documents工具
数据流注意事项:连接别名和密码

使用add-connection-alias工具添加新的连接别名时,如果您使用的是远程 LLM 提供程序,请避免将别名添加到包含密码的 URI。由于您的请求会发送到 LLM,因此 URI 中的任何密码都可能被泄露。建议您在 MongoDB Lens配置文件中定义包含密码的别名,这样别名会保留在本地,不会传输到 LLM。

数据流考虑:本地设置以实现最大安全性

虽然超出了本文档的讨论范围,但为了获得最高级别的数据隐私,请考虑使用本地 MCP 客户端搭配本地托管的 LLM 模型。这种方法将所有请求和数据保留在本地环境中,从而消除了敏感信息被发送到远程提供商的风险。

数据保护:破坏性操作的确认

MongoDB Lens 针对潜在的破坏性操作实现了基于令牌的确认系统,需要两步过程来执行可能导致不受控制的数据丢失的工具:

  1. 第一次工具调用:返回一个 4 位数的确认令牌,该令牌在 5 分钟后过期
  2. 第二次工具调用:如果提供了有效的令牌,则执行操作

有关确认过程的示例,请参阅:使用确认保护

需要确认的工具包括:

  • drop-user :删除数据库用户
  • drop-index :删除索引(可能影响性能)
  • drop-database :永久删除数据库
  • drop-collection :删除集合及其所有文档
  • delete-document :删除一个或多个文档
  • bulk-operations :包括删除操作时
  • rename-collection :当目标集合存在时将被删除

此保护机制旨在防止因输入错误或误操作导致意外数据丢失。它就像一道安全网,确保您在执行可能造成危害的操作之前了解其后果。

[!NOTE] 如果您在可以接受数据丢失的受控环境中工作,则可以配置 MongoDB Lens 以绕过确认并立即执行破坏性操作。

绕过破坏性操作的确认

您可能想要绕过令牌确认系统。

将环境变量CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS设置为true ,即可立即执行破坏性操作而无需确认:

# Using NPX CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS=true npx -y mongodb-lens@latest # Using Docker docker run --rm -i --network=host --pull=always -e CONFIG_DISABLE_DESTRUCTIVE_OPERATION_TOKENS='true' furey/mongodb-lens

禁用确认令牌会移除一项重要的安全机制。强烈建议仅在可接受数据丢失的受控环境中使用此选项,例如开发或测试环境。禁用此选项风险自负。

数据保护:禁用破坏性操作

禁用工具

MongoDB Lens 包含几个可以修改或删除数据的工具。要禁用特定工具,请将它们添加到配置文件中的disabled.tools数组中:

{ "disabled": { "tools": [ "drop-user", "drop-index", "drop-database", "drop-collection", "delete-document", "bulk-operations", "rename-collection" ] } }

[!NOTE] 还可以通过disabled.resourcesdisabled.prompts设置禁用资源和提示。

高风险工具

这些工具可能会导致立即的数据丢失,应考虑在敏感环境中禁用:

  • drop-user :删除数据库用户及其访问权限
  • drop-index :删除索引(可能会影响查询性能)
  • drop-database :永久删除整个数据库
  • drop-collection :永久删除集合及其所有文档
  • delete-document :删除符合指定条件的文档
  • bulk-operations :配置后可以执行批量删除
  • rename-collection :使用 drop target 选项时可以覆盖现有集合
中等风险工具

这些工具可以修改数据,但通常不会导致立即的数据丢失:

  • create-user :创建具有可进行进一步更改的权限的用户
  • transaction :在一个事务中执行多个操作(可能存在复杂的变化)
  • update-document :更新可能覆盖现有数据的文档
只读配置

要获得完整的只读配置,请禁用所有可能具有破坏性的工具:

{ "disabled": { "tools": [ "drop-user", "drop-index", "create-user", "transaction", "create-index", "drop-database", "drop-collection", "insert-document", "update-document", "delete-document", "bulk-operations", "create-database", "gridfs-operation", "create-collection", "rename-collection", "create-timeseries" ] } }

此配置允许 MongoDB Lens 查询和分析数据,同时防止任何修改,提供多层保护以防止意外数据丢失。

选择性组件启用

除了禁用组件之外,还可以使用配置文件中的enabled设置来精确指定应启用哪些组件(隐式禁用所有其他组件):

{ "enabled": { "tools": [ "use-database", "find-documents", "count-documents", "aggregate-data" ] }, "disabled": { "resources": true, "prompts": true } }

[!IMPORTANT] 如果组件同时出现在enableddisabled列表中,则enabled设置优先。

教程

以下教程将指导您设置包含示例数据的 MongoDB 容器,然后使用 MongoDB Lens 通过自然语言查询与其进行交互:

  1. 启动示例数据容器
  2. 导入样本数据
  3. 连接 MongoDB Lens
  4. 示例查询
  5. 使用确认保护

教程:1. 启动示例数据容器

[!NOTE] 本教程假设您已在系统上安装并运行Docker

[!IMPORTANT] 如果 Docker 已在端口 27017 上运行容器,请先停止它再继续。

  1. 初始化示例数据容器:
    docker run --name mongodb-sampledata -d -p 27017:27017 mongo:6
  2. 验证容器是否正常运行:
    docker ps | grep mongodb-sampledata

教程:2. 导入示例数据

MongoDB 提供了几个示例数据集,我们将使用它们来探索 MongoDB Lens。

  1. 下载示例数据集:
    curl -LO https://atlas-education.s3.amazonaws.com/sampledata.archive
  2. 将示例数据集复制到示例数据容器中:
    docker cp sampledata.archive mongodb-sampledata:/tmp/
  3. 将示例数据集导入 MongoDB:
    docker exec -it mongodb-sampledata mongorestore --archive=/tmp/sampledata.archive

这将导入几个数据库:

  • sample_airbnb :Airbnb 房源和评论
  • sample_analytics :客户和账户数据
  • sample_geospatial :地理数据
  • sample_mflix :电影数据
  • sample_restaurants :餐厅数据
  • sample_supplies :供应链数据
  • sample_training :各种应用的训练数据
  • sample_weatherdata :天气测量

教程:3. 连接 MongoDB Lens

按照快速入门说明安装MongoDB Lens。

设置您的MCP 客户端通过以下方式连接到 MongoDB Lens: mongodb://localhost:27017

[!TIP] 从 MCP 客户端配置中省略连接字符串将使连接字符串默认为mongodb://localhost:27017

Claude 桌面配置示例:

{ "mcpServers": { "mongodb-lens": { "command": "/path/to/npx", "args": [ "-y", "mongodb-lens@latest" ] } } }

教程:4. 示例查询

在 MCP 客户端运行并连接到 MongoDB Lens 的情况下,尝试以下示例查询:

示例查询:基本数据库操作
  • “列出所有数据库” ➥使用list-databases工具
  • “我目前使用什么数据库?” ➥ 使用current-database工具
  • “切换到 sample_mflix 数据库” ➥ 使用use-database工具
  • “创建一个名为 test_db 的���数据库” ➥使用create-database工具
  • “创建另一个名为 analytics_db 的数据库并切换到它” ➥ 使用create-database工具并设置 switch=true
  • “Drop test_db” ➥使用drop-database工具(需确认)
示例查询:集合管理
  • “当前数据库中有哪些馆藏?” ➥ 使用list-collections工具
  • “创建 user_logs 集合” ➥ 使用create-collection工具
  • “将 user_logs 重命名为 system_logs” ➥ 使用rename-collection工具
  • “Drop system_logs” ➥使用drop-collection工具(需确认)
  • “检查电影集合中的数据一致性” ➥使用validate-collection工具
示例查询:用户管理
  • “创建只读用户进行分析” ➥使用create-user工具
  • “删除非活动用户帐户” ➥使用drop-user工具(需确认)
示例查询:查询数据
  • “统计电影集合中的所有文档” ➥使用count-documents工具
  • “查找 IMDB 评分最高的 5 部电影” ➥ 使用find-documents工具
  • “显示按年代分组的电影汇总数据” ➥ 使用aggregate-data工具
  • “列出所有制作电影的特定国家” ➥ 使用distinct-values工具
  • “搜索片名包含《教父》的电影” ➥ 使用text-search工具
  • “使用适当的排序规则查找姓氏为 müller 的德国用户” ➥ 使用collation-query工具
示例查询:模式分析
  • “电影集合的架构是什么样的?” ➥ 使用analyze-schema工具
  • “比较用户和评论模式” ➥使用compare-schemas工具
  • “为电影集合生成一个模式验证器” ➥使用generate-schema-validator工具
  • “分析电影集合的常见查询模式” ➥使用analyze-query-patterns工具
示例查询:数据修改
  • “插入新电影文档:<您的字段数据>” ➥使用insert-document工具
  • “更新 1994 年以来的所有电影,添加‘经典’标记” ➥ 使用update-document工具
  • “删除所有零评分的电影” ➥使用delete-document工具(需确认)
  • “对电影集合运行这些批量操作:<你的 JSON 数据>” ➥ 使用bulk-operations工具

[!TIP] 对于专门的 MongoDB 操作(如数组操作、按位操作或其他复杂更新),请通过update-document工具的updateoptions参数使用 MongoDB 的本机运算符。

示例查询:性能和索引管理
  • “在电影集合的标题字段上创建索引” ➥使用create-index工具
  • “删除 ratings_idx 索引” ➥ 使用drop-index工具(需确认)
  • “解释查找 1995 年电影的执行计划” ➥ 使用explain-query工具
  • “获取当前数据库的统计信息” ➥ 使用get-stats工具,目标为数据库
  • “显示电影收藏的统计信息” ➥ 使用带有 target=collection 的get-stats工具
示例查询:地理空间和特殊操作
  • “切换到 sample_geospatial db,然后查找坐标 [-80.12, 26.46] 10 公里范围内的所有沉船” ➥ 使用geo-query工具
  • “切换到 sample_analytics db,然后执行交易以在账户之间转移资金: ➥ 使用transaction工具
  • “为传感器读数创建时间序列集合” ➥使用create-timeseries工具
  • “观察用户集合中的变化 30 秒” ➥ 使用watch-changes工具
  • “列出图像 GridFS 存储桶中的所有文件” ➥ 使用gridfs-operation工具并指定 operation=list
示例查询:导出、管理和其他功能
  • 切换到 sample_mflix db,然后根据‘tomatoes.critic.rating’将排名前 20 的电影导出为 CSV 文件,其中包含标题、年份和评级字段(在单个代码块中输出)” ➥ 使用export-data工具
  • “切换到 sample_analytics db,然后检查其分片状态” ➥ 使用shard-status工具
  • “清除集合缓存” ➥ 使用带有 target=collections 的clear-cache工具
  • “清除所有缓存” ➥ 使用clear-cache工具
  • “切换到 sample_weatherdata db,然后生成关于其当前状态的交互式报告” ➥ 使用多种工具
示例查询:连接管理
  • “连接到 mongodb://localhost:27018” ➥ 使用connect-mongodb工具
  • “连接到 mongodb+srv://username: password@cluster.mongodb.net /mydb” ➥使用connect-mongodb工具
  • “连接回原始 mongodb 实例” ➥ 使用connect-original工具
  • “连接到副本集而不验证连接:<副本集详细信息>” ➥ 使用connect-mongodb工具并设置validateConnection=false
  • “为 mongodb://username:password@prod-server:27017/mydb 添加连接别名‘prod’” ➥ 使用add-connection-alias工具

教程:5. 使用确认保护

MongoDB Lens 包含针对潜在破坏性操作的安全机制。其实际运作方式如下:

  1. 删除集合的请求:
    "Drop the collection named test_collection"
  2. MongoDB Lens 以警告和确认令牌进行响应:
    ⚠️ DESTRUCTIVE OPERATION WARNING ⚠️ You've requested to drop the collection 'test_collection'. This operation is irreversible and will permanently delete all data in this collection. To confirm, you must type the 4-digit confirmation code EXACTLY as shown below: Confirmation code: 9876 This code will expire in 5 minutes for security purposes.
  3. 通过提交确认令牌来确认操作:
    "9876"
  4. MongoDB Lens 执行操作:
    Collection 'test_collection' has been permanently deleted.

此两步过程通过要求明确确认来防止意外的数据丢失。

[!NOTE] 如果您在可以接受数据丢失的受控环境中工作,则可以配置 MongoDB Lens 以绕过确认并立即执行破坏性操作。

测试套件

MongoDB Lens 包含一个测试套件,用于验证工具、资源和提示的功能。

测试套件:运行测试

测试套件需要一个CONFIG_MONGO_URI环境变量,可以将其设置为:

  • MongoDB 连接字符串(例如mongodb://localhost:27017
  • mongodb-memory-server (用于内存测试)
# Run Tests with MongoDB Connection String CONFIG_MONGO_URI=mongodb://localhost:27017 node mongodb-lens.test.js # Run Tests with In-Memory MongoDB (requires mongodb-memory-server) CONFIG_MONGO_URI=mongodb-memory-server node mongodb-lens.test.js

为了方便起见,可以使用以下脚本来运行测试:

npm test # Fails if no CONFIG_MONGO_URI provided npm run test:localhost # Uses mongodb://localhost:27017 npm run test:localhost:verbose # Runs with DEBUG=true for verbose output npm run test:in-memory # Uses mongodb-memory-server npm run test:in-memory:verbose # Runs with DEBUG=true for verbose output

[!NOTE] 测试套件会创建临时数据库和集合,这些数据库和集合会在测试完成后清理。

测试套件:命令行选项

选项描述
--list列出所有可用的测试但不运行它们
--test=<n>按名称运行特定测试(以逗号分隔)
--group=<n>运行特定组中的所有测试(以逗号分隔)
--pattern=<glob>运行匹配模式的测试(以逗号分隔)

测试套件:示例

# List All Available Tests npm test -- --list # Run Only Connection-Related Tests (:27017) npm run test:localhost -- --group=Connection\ Tools # Test Specific Database Operations (In-Memory) npm run test:in-memory -- --test=create-database\ Tool,drop-database\ Tool # Test All Document-Related Tools (:27017) npm run test:localhost -- --pattern=document # Run Resource Tests Only (In-Memory) npm run test:in-memory -- --group=Resources # Run Specific Tests Only (In-Memory) npm run test:in-memory -- --test=aggregate-data\ Tool,find-documents\ Tool

免责声明

MongoDB 透视图:

  • 是根据MIT 许可证授权的。
  • 与 MongoDB, Inc. 没有任何关联或认可。
  • 是在人工智能的帮助下编写的,可能包含错误。
  • 仅用于教育和实验目的。
  • 按原样提供,不提供任何担保 - 请自行承担使用风险。

支持

如果您发现 MongoDB Lens 有帮助,请考虑通过以下方式支持我的工作:

给我买杯咖啡| GitHub 赞助

贡献帮助我继续开发和改进这个工具,让我可以投入更多的时间来添加新功能,并确保它仍然是社区的宝贵资源。

Related MCP Servers

  • -
    security
    A
    license
    -
    quality
    A Model Context Protocol (MCP) server that enables LLMs to interact directly with MongoDB databases. Query collections, inspect schemas, and manage data seamlessly through natural language.
    Last updated -
    340
    75
    TypeScript
    MIT License
    • Apple
  • A
    security
    A
    license
    A
    quality
    An MCP server that provides tools for interacting with Supabase databases, storage, and edge functions.
    Last updated -
    14
    41
    JavaScript
    MIT License
  • -
    security
    A
    license
    -
    quality
    An MCP server that enables users to create and manage MongoDB Atlas clusters, users, and network access through natural language commands.
    Last updated -
    74
    10
    JavaScript
    MIT License
    • Apple
    • Linux
  • -
    security
    A
    license
    -
    quality
    An MCP server that enables large language models to interact directly with MongoDB databases, allowing them to query collections, inspect schemas, and manage data through natural language.
    Last updated -
    340
    MIT License
    • Apple

View all related MCP servers

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/furey/mongodb-lens'

If you have feedback or need assistance with the MCP directory API, please join our Discord server