mcpField
M
MongoDB Lens

MongoDB Lens

本地服务
npmjs.com数据库20879 周前更新

关于 MongoDB Lens

MongoDB Lens 是一个本地运行的 MCP 服务,让 AI 助手通过自然语言访问 MongoDB 数据库。它面向需要查询、聚合、分析性能和管理数据库的开发者与运维人员,并提供较完整的工具、资源和提示词集合。

主要功能

  1. 01自然语言查询与聚合管道执行
  2. 02查询模式分析与索引优化建议
  3. 03模式推断、模式比较与校验器生成
  4. 04破坏性操作需二次确认
  5. 05多连接别名切换与断线自动重连

适用场景

  1. 01通过 AI 客户端探索和查询 MongoDB 数据
  2. 02分析慢查询并获取索引优化建议
  3. 03在确认后执行批量写入或删除操作

MCP 相关

该项目是 MCP 服务,向 MCP 客户端暴露 40 余个 工具、12 个资源和 14 个提示词,用于操作 MongoDB。

配置

本地服务的配置在各客户端中通用,复制后粘贴到客户端的 MCP 配置文件即可。

暂未收录安装方式

我们还没有获取到这个服务的安装包或远程地址,请按项目 README 中的说明安装。

代码仓库

工具

还没有获取到工具列表

本地服务需要在你的电脑上运行后才能读取工具,维护者暂未提供工具列表。

详细介绍

MongoDB Lens

License Docker Hub Version NPM Version Buy Me a Coffee

MongoDB Lens 是一个本地 Model Context Protocol(MCP)服务,可通过大模型使用自然语言全面访问 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

说明


系统需要安装并运行 Node.js 才能使用 NPX(建议使用 Volta)。

使用 NPX 运行 MongoDB Lens 是最简单的方式。

首先,确保已安装 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

提示


如果使用 npx 时遇到权限错误,请尝试先运行 npx clear-npx-cache,再运行 npx -y mongodb-lens(这会清除缓存并重新下载软件包)。

安装:Docker Hub

说明


系统需要安装并运行 Docker 才能使用 Docker Hub。

首先,确保已安装 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

说明


从源代码安装 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

说明


从源代码构建 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 消息粘贴到服务的标准输入中并运行:

{"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 实例兼容的旧版驱动程序。

说明


你可能还需要还原此提交,以重新添加 useNewUrlParser 和 useUnifiedTopology 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 [email protected]

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

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

配置:配置文件

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

说明


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

提示


配置文件中只需包含你想自定义的设置。对于任何省略的值,MongoDB Lens 都将使用默认设置。

提示


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:[email protected]/mydb"
  }
}

使用此配置时:

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

说明


使用命令行参数指定连接时,你可以使用完整的 MongoDB URI,也可以使用配置文件中定义的别名。

提示


要在运行时添加连接别名,请使用 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. 全局安装 cross-env:
    # 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

要在 Claude Desktop 中使用 MongoDB Lens:

  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 Desktop
  5. 与 Claude 开始对话,讨论你的 MongoDB 数据
Claude Desktop 配置选项

对于每个选项:

  • 将 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 Inspector

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

说明


MCP Inspector 会在端口 3000 上启动代理服务,并在端口 5173 上启动 Web 客户端。

NPX 使用示例:

  1. 运行 MCP Inspector:
    # 使用默认连接字符串 mongodb://localhost:27017
    npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
    
    # 使用自定义连接字符串
    npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest mongodb://your-connection-string
    
    # 使用自定义端口
    SERVER_PORT=1234 CLIENT_PORT=5678 npx -y @modelcontextprotocol/inspector npx -y mongodb-lens@latest
    
  2. 打开 MCP Inspector:http://localhost:5173

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

更多信息,请参阅:MCP Inspector

客户端设置:其他 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)。

这种方法为你提供了一个沙盒,可用于测试复杂或破坏性操作,而无需担心意外损坏实时数据。

数据保护:数据流注意事项
数据流注意事项:数据如何在系统中流动

使用 MCP 服务搭配远程大模型提供商(例如通过 Claude Desktop 使用 Anthropic)时,了解数据如何在系统中流动,是防止敏感信息意外泄露的关键。

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

说明


尽管此示例使用本地 MongoDB 实例,但同样的原则也适用于远程 MongoDB 实例。

sequenceDiagram
    actor User
    box Local Machine #d4f1f9
        participant Client as MCP Client
        participant Lens as MongoDB Lens
        participant MongoDB as MongoDB Instance
    end
    box Remote Server #ffe6cc
        participant LLM as Remote LLM Provider
    end

    User->>Client: 1. Submit request<br>"Show me all users older than 30"
    Client->>LLM: 2. User request + available tools
    Note over LLM: Interprets request<br>Chooses appropriate tool
    LLM->>Client: 3. Tool selection (find-documents)
    Client->>Lens: 4. Tool run with parameters
    Lens->>MongoDB: 5. Database query
    MongoDB-->>Lens: 6. Database results
    Lens-->>Client: 7. Tool results (formatted data)
    Client->>LLM: 8. Tool results
    Note over LLM: Processes results<br>Formats response
    LLM-->>Client: 9. Processed response
    Client-->>User: 10. Final answer
  1. 你提交请求
    ➥ 例如:“显示所有年龄超过 30 岁的用户”
  2. 客户端将请求发送给远程大模型
    ➥ 大模型提供商会收到你的原话,以及可用 MCP 工具及其参数列表。
  3. 远程大模型解析你的请求
    ➥ 它会判断你的意图,并指示客户端使用具有适当参数的特定 MCP 工具。
  4. 客户端请求 MongoDB Lens 运行该工具
    ➥ 此过程通过 stdio 在你的计算机本地执行。
  5. MongoDB Lens 查询 MongoDB 数据库
  6. MongoDB Lens 获取 MongoDB 查询结果
  7. MongoDB Lens 将数据发回客户端
    ➥ 客户端会收到由 MongoDB Lens 格式化的结果。
  8. 客户端将数据转发给远程大模型
    ➥ 大模型提供商会看到 MongoDB Lens 返回的确切数据。
  9. 远程大模型处理数据
    ➥ 它可能会进一步汇总或格式化结果。
  10. 远程大模型将最终响应发送给客户端
    ➥ 客户端会向你显示答案。

远程大模型提供商会同时看到你的原始请求和 MongoDB Lens 返回的完整内容。如果数据库包含敏感字段(例如密码、个人信息等),除非采取预防措施,否则这些数据可能会被意外传输给远程提供商。

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

为防止敏感数据发送给远程大模型提供商,使用 find-documents、aggregate-data 或 export-data 等工具时,请采用投影。投影允许你指定在查询结果中包含或排除哪些字段,确保敏感信息留在本地。

投影用法示例:

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

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

数据流注意事项:为最高安全性进行本地设置

虽然这不在本文档的讨论范围内,但为了最大限度地保护数据隐私,可以考虑使用本地 MCP 客户端,并搭配在本地托管的 LLM 模型。这样,所有请求和数据都会留在本地环境中,从而消除敏感信息被发送给远程提供商的风险。

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

MongoDB Lens 实现了基于令牌的确认系统,用于可能具有破坏性的操作。执行可能导致数据未受检查地丢失的工具时,必须经过两个步骤:

  1. 首次调用工具:返回一个有效期为 5 分钟的 4 位确认令牌
  2. 再次调用工具:如果提供了有效令牌,则执行操作

确认流程示例请参见:使用确认保护

需要确认的工具包括:

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

此保护机制旨在防止因拼写错误和意外命令导致的数据意外丢失。它是一道安全网,可确保你在执行可能有害的操作前了解其后果。

说明


如果你在允许数据丢失的受控环境中工作,可以将 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"
    ]
  }
}

说明


也可以通过 disabled.resources 和 disabled.prompts 设置禁用资源和提示词。

高风险工具

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

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

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

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

重要


如果某个组件同时出现在 enabled 和 disabled 列表中,则以 enabled 设置为准。

教程

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

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

说明


本教程假设你已在系统上安装并运行 Docker。

重要


如果 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

提示


如果在 MCP 客户端配置中省略连接字符串,则默认使用 mongodb://localhost:27017。

Claude Desktop 配置示例:

{
  "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 的数据库并切换到该数据库”
    ➥ 使用带有 switch=true 的 create-database 工具
  • “删除 test_db”
    ➥ 使用 drop-database 工具(需确认)
示例查询:集合管理
  • “当前数据库中有哪些集合?”
    ➥ 使用 list-collections 工具
  • “创建 user_logs 集合”
    ➥ 使用 create-collection 工具
  • “将 user_logs 重命名为 system_logs”
    ➥ 使用 rename-collection 工具
  • “删除 system_logs”
    ➥ 使用 drop-collection 工具(需确认)
  • “检查 movies 集合中的数据一致性”
    ➥ 使用 validate-collection 工具
示例查询:用户管理
  • “为 analytics 创建一个只读用户”
    ➥ 使用 create-user 工具
  • “删除 inactive_user 帐户”
    ➥ 使用 drop-user 工具(需确认)
示例查询:查询数据
  • “统计 movies 集合中的所有文档”
    ➥ 使用 count-documents 工具
  • “查找 IMDB 评分最高的 5 部电影”
    ➥ 使用 find-documents 工具
  • “显示按年代分组的电影聚合数据”
    ➥ 使用 aggregate-data 工具
  • “列出所有电影制作地的唯一国家/地区”
    ➥ 使用 distinct-values 工具
  • “搜索标题中包含 godfather 的电影”
    ➥ 使用 text-search 工具
  • “使用正确的排序规则查找姓氏为 müller 的德国用户”
    ➥ 使用 collation-query 工具
示例查询:架构分析
  • “movies 集合的架构结构是什么?”
    ➥ 使用 analyze-schema 工具
  • “比较 users 和 comments 的架构”
    ➥ 使用 compare-schemas 工具
  • “为 movies 集合生成架构验证器”
    ➥ 使用 generate-schema-validator 工具
  • “分析 movies 集合的常见查询模式”
    ➥ 使用 analyze-query-patterns 工具
示例查询:数据修改
  • "插入新的电影文档:<your field data>"
    ➥ 使用 insert-document 工具
  • "为 1994 年的所有电影添加一个 'classic' 标记"
    ➥ 使用 update-document 工具
  • "删除所有评分为零的电影"
    ➥ 使用 delete-document 工具(需确认)
  • "对 movies 集合执行这些批量操作:<your JSON data>"
    ➥ 使用 bulk-operations 工具

提示


对于专门的 MongoDB 操作(例如数组操作、位运算或其他复杂更新),请通过 update-document 工具的 update 和 options 参数使用 MongoDB 原生运算符。

示例查询:性能与索引管理
  • "在 movies 集合的 title 字段上创建索引"
    ➥ 使用 create-index 工具
  • "删除 ratings_idx 索引"
    ➥ 使用 drop-index 工具(需确认)
  • "说明查找 1995 年电影的执行计划"
    ➥ 使用 explain-query 工具
  • "获取当前数据库的统计信息"
    ➥ 使用 get-stats 工具,参数为 target=database
  • "显示 movies 集合的统计信息"
    ➥ 使用 get-stats 工具,参数为 target=collection
示例查询:地理空间与特殊操作
  • "切换到 sample_geospatial 数据库,然后查找距坐标 [-80.12, 26.46] 10km 范围内的所有沉船"
    ➥ 使用 geo-query 工具
  • "切换到 sample_analytics 数据库,然后执行事务,在账户之间转移资金:<account ids>"
    ➥ 使用 transaction 工具
  • "为传感器读数创建时间序列集合"
    ➥ 使用 create-timeseries 工具
  • "监视 users 集合中的变更,持续 30 秒"
    ➥ 使用 watch-changes 工具
  • "列出 images GridFS 存储桶中的所有文件"
    ➥ 使用 gridfs-operation 工具,参数为 operation=list
示例查询:导出、管理与其他功能
  • "切换到 sample_mflix 数据库,然后根据 'tomatoes.critic.rating' 导出评分最高的 20 部电影,导出为包含 title、year 和 rating 字段的 CSV(在单个代码块中输出)"
    ➥ 使用 export-data 工具
  • "切换到 sample_analytics 数据库,然后检查其分片状态"
    ➥ 使用 shard-status 工具
  • "清除集合缓存"
    ➥ 使用 clear-cache 工具,参数为 target=collections
  • "清除所有缓存"
    ➥ 使用 clear-cache 工具
  • "切换到 sample_weatherdata 数据库,然后生成一份关于其当前状态的交互式报告"
    ➥ 使用多个工具
示例查询:连接管理
  • "连接到 mongodb://localhost:27018"
    ➥ 使用 connect-mongodb 工具
  • "连接到 mongodb+srv://username:[email protected]/mydb"
    ➥ 使用 connect-mongodb 工具
  • "重新连接到原始 mongodb 实例"
    ➥ 使用 connect-original 工具
  • "连接到副本集,但不验证连接:<replica set details>"
    ➥ 使用 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.
    

这个两步流程要求用户明确确认,可避免意外数据丢失。

说明


如果你在允许数据丢失的受控环境中工作,可以配置 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

说明


测试套件会创建临时数据库和集合,并在测试完成后清理它们。

测试套件:命令行选项
选项说明
--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 Lens:

  • 采用 MIT 许可证授权。
  • 与 MongoDB, Inc. 无关联,也未获得其认可。
  • 在 AI 的协助下编写,可能包含错误。
  • 仅用于教育和实验目的。
  • 按“原样”提供,不附带任何保证——使用风险由你自行承担。

支持

如果你觉得 MongoDB Lens 有帮助,请通过以下方式支持我的工作:

请我喝杯咖啡 | GitHub 赞助

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

评论

支持 Markdown

第一次接触 MCP?

从协议是什么,到在客户端里装上第一个服务,这几条回答覆盖了大多数入门问题。

一个开放协议,规定了 AI 应用如何以统一方式连接外部工具与数据源。客户端负责与模型对话,MCP 服务负责提供工具、资源和提示模板,两者通过标准消息通信,同一个服务可以被不同客户端复用。