/ Каталог / Песочница / MongoDB
● Официальный mongodb-js 🔑 Нужен свой ключ

MongoDB

автор mongodb-js · mongodb-js/mongodb-mcp-server

Let Claude query, aggregate, and administer MongoDB Atlas or self-hosted clusters — with read-only defaults you can relax per-tool.

MongoDB's official MCP covers both the driver (CRUD + aggregation on any cluster) and the Atlas control plane (list projects, clusters, users). By default it runs in read-only mode; enable writes explicitly per command family when you need them.

Зачем использовать

Ключевые функции

Живое демо

Как выглядит на практике

mongodb.replay ▶ готово
0/0

Установка

Выберите клиент

~/Library/Application Support/Claude/claude_desktop_config.json  · Windows: %APPDATA%\Claude\claude_desktop_config.json
{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server"
      ]
    }
  }
}

Откройте Claude Desktop → Settings → Developer → Edit Config. Перезапустите после сохранения.

~/.cursor/mcp.json · .cursor/mcp.json
{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server"
      ]
    }
  }
}

Cursor использует ту же схему mcpServers, что и Claude Desktop. Конфиг проекта приоритетнее глобального.

VS Code → Cline → MCP Servers → Edit
{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server"
      ]
    }
  }
}

Щёлкните значок MCP Servers на боковой панели Cline, затем "Edit Configuration".

~/.codeium/windsurf/mcp_config.json
{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server"
      ]
    }
  }
}

Тот же формат, что и Claude Desktop. Перезапустите Windsurf для применения.

~/.continue/config.json
{
  "mcpServers": [
    {
      "name": "mongodb",
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server"
      ]
    }
  ]
}

Continue использует массив объектов серверов, а не map.

~/.config/zed/settings.json
{
  "context_servers": {
    "mongodb": {
      "command": {
        "path": "npx",
        "args": [
          "-y",
          "mongodb-mcp-server"
        ]
      }
    }
  }
}

Добавьте в context_servers. Zed перезагружается автоматически.

claude mcp add mongodb -- npx -y mongodb-mcp-server

Однострочная команда. Проверить: claude mcp list. Удалить: claude mcp remove.

Сценарии использования

Реальные сценарии: MongoDB

Answer business questions with Mongo aggregation pipelines

👤 PMs and analysts on a Mongo-backed product ⏱ ~15 min beginner

Когда использовать: You need counts, funnels, or top-N lists and don't want to learn $group/$lookup syntax.

Предварительные требования
  • Read-only connection string — Atlas: create a DB user with readAnyDatabase. Self-hosted: user with read role on relevant DBs.
Поток
  1. Discover collections
    List databases, then for app_prod list all collections and their approximate document counts.✓ Скопировано
    → Collection catalog
  2. Sample and infer schema
    Sample 20 docs from users and orders. Describe the fields and types you see.✓ Скопировано
    → Per-collection schema description
  3. Run the actual aggregation
    How many orders were placed per country in the last 30 days? Sort desc and limit 20.✓ Скопировано
    → Results table with the pipeline used

Итог: Business answers with the exact pipeline preserved for re-running.

Подводные камни
  • Aggregations without indexes can scan huge collections — Always check .explain() first and make sure a supporting index exists; otherwise add $match narrowly on an indexed field at the top of the pipeline
Сочетать с: notion

Infer and document a messy collection's actual schema

👤 New engineer onboarding to an undocumented Mongo ⏱ ~25 min intermediate

Когда использовать: The collection was 'schemaless' for 3 years and nobody knows which fields actually exist.

Поток
  1. Sample broadly
    Sample 500 docs from events. For each top-level field, report presence %, type(s), and a sample value.✓ Скопировано
    → Field-by-field presence/type matrix
  2. Find schema drift
    Which fields have multiple types across docs? Group by (field, type) and count.✓ Скопировано
    → List of polymorphic fields
  3. Produce a TypeScript type or JSON schema
    Generate a TypeScript interface for the 'stable' fields (≥95% presence, single type). Mark the rest as optional or unknown.✓ Скопировано
    → Usable type definition

Итог: A documented schema with known quirks — the basis for migrations or a validator.

Подводные камни
  • 500 docs may miss rare but important variants — Sample by time bucket (one per month) to catch legacy shapes
Сочетать с: filesystem

Audit your Atlas projects for security and cost

👤 DevOps/platform teams on Atlas ⏱ ~20 min intermediate

Когда использовать: Quarterly: check which clusters are oversized, which have wide IP allowlists, who has access.

Предварительные требования
  • Atlas API public+private key — cloud.mongodb.com → Organization Access → API keys; project-scoped
Поток
  1. List projects + clusters
    List every project and within each, every cluster with its tier, region, and backup status.✓ Скопировано
    → Full inventory
  2. Flag risky access
    For each project, dump the IP access list. Flag any entry of 0.0.0.0/0 with the project name.✓ Скопировано
    → Risky-access report
  3. Suggest rightsizing
    Any cluster on M30+ with fewer than 10GB used? Recommend downgrades.✓ Скопировано
    → Cost-savings list

Итог: A short remediation list for your security + finance folks.

Подводные камни
  • API key scope too narrow to see every project — Use an Organization-level key in read-only mode rather than a project-level one
Сочетать с: notion

Propose and execute a one-off data cleanup safely

👤 Backend engineer fixing a data bug ⏱ ~30 min advanced

Когда использовать: A bug caused bad writes; you need to fix ~10k docs but must not nuke the wrong ones.

Предварительные требования
  • Writable user (scoped to the target DB only) — Atlas: role with readWrite on that one DB, nothing else
  • --read-only OFF explicitly for this session — Start the MCP without --read-only
Поток
  1. Scope the fix with a count
    Count docs in users where status='active' AND last_login IS NULL AND created_at < 2024-01-01. Don't modify anything.✓ Скопировано
    → Expected-affected count, e.g. 9,873
  2. Dry-run the update
    Show the updateMany pipeline you would run (filter + $set), and show 5 sample docs that would be changed. Do NOT execute.✓ Скопировано
    → Filter + set preview
  3. Execute with a limit and verify
    Run the update. Then re-run the original count — it should be 0. Report matchedCount and modifiedCount.✓ Скопировано
    → Counts match expectation; verify query returns 0

Итог: A clean, auditable fix with counts before and after.

Подводные камни
  • updateMany with a bad filter nukes the whole collection — Always run the filter as countDocuments first; if the count is surprising, stop and investigate
  • No backup of the affected slice — Copy the matching docs to a <collection>_backup_<date> collection before updating
Сочетать с: filesystem

Suggest missing indexes from slow-query patterns

👤 Backend engineers hunting perf issues ⏱ ~25 min advanced

Когда использовать: Your app is slow on Mongo queries; you want a targeted index plan, not a shotgun.

Поток
  1. Check existing indexes
    For orders and users, list every index with its keys and size on disk.✓ Скопировано
    → Index catalog
  2. Profile a specific query
    Run .explain('executionStats') on this query [paste]. Report totalDocsExamined vs nReturned and the winning plan stage.✓ Скопировано
    → Explain output
  3. Propose the smallest new index
    Given that plan, propose exactly one index that would convert this to IXSCAN. Justify field order.✓ Скопировано
    → Concrete createIndex command with rationale

Итог: A single, justifiable index recommendation per slow query — not a wall of them.

Подводные камни
  • Over-indexing kills write throughput and balloons storage — Only add an index that serves >1 high-traffic query; compound indexes should reflect ESR (Equality, Sort, Range) order

Комбинации

Сочетайте с другими MCP — эффект x10

mongodb + notion

Aggregate, then post a shareable report

Compute MAU per plan tier for the last 6 months and create a Notion page in 'Growth / Monthly' with the results as a table.✓ Скопировано
mongodb + filesystem

Backup a collection slice as JSONL before a cleanup

Find all docs in users matching <filter>, save to /backups/users-cleanup-<date>.jsonl, then delete them.✓ Скопировано
mongodb + postgres

Cross-DB reconciliation when migrating off Mongo

For every user_id in Mongo users, check whether a corresponding row exists in Postgres users. Report mismatches.✓ Скопировано

Инструменты

Что предоставляет этот MCP

ИнструментВходные данныеКогда вызыватьСтоимость
list_databases Start of any exploration session free
list_collections database: str Inventory a database free
find database, collection, filter?, projection?, sort?, limit? Read documents — the main read workhorse free
aggregate database, collection, pipeline: stage[] Grouping, joining, analytics free
count database, collection, filter? Always before destructive writes — confirm scope free
insert_one / insert_many database, collection, document(s) Requires --read-only off writes
update_one / update_many database, collection, filter, update Always preview filter with count first writes
delete_one / delete_many database, collection, filter Dangerous — require explicit user confirmation writes
list_indexes database, collection Perf analysis before suggesting new indexes free
atlas_list_projects / atlas_list_clusters Atlas control-plane audits free

Стоимость и лимиты

Во что обходится

Квота API
Driver: bounded by cluster connection limit. Atlas API: 100 req/min per key.
Токенов на вызов
Find/aggregate: scales with result size; use projections and limits.
Деньги
Free against your existing cluster. Atlas has a free M0 tier for testing.
Совет
Always project only the fields you need; unbounded finds return large docs that chew context and egress.

Безопасность

Права, секреты, радиус поражения

Минимальные скоупы: readAnyDatabase (read-only) or read on specific DBs
Хранение учётных данных: MDB_MCP_CONNECTION_STRING for driver; MDB_MCP_API_CLIENT_ID + MDB_MCP_API_CLIENT_SECRET for Atlas
Исходящий трафик: Driver connects to your cluster; Atlas API to cloud.mongodb.com only
Никогда не давайте: dbAdminAnyDatabase userAdminAnyDatabase root

Устранение неполадок

Частые ошибки и исправления

MongoServerError: Authentication failed

Connection string user/password wrong or the user lacks auth DB. Add ?authSource=admin for Atlas.

Проверить: mongosh '$MDB_MCP_CONNECTION_STRING' --eval 'db.runCommand({ping:1})'
MongoNetworkError: ETIMEDOUT

IP not in Atlas allowlist. Add your current IP in Atlas → Network Access.

Проверить: curl ifconfig.me then compare
not authorized on admin to execute command listDatabases

Role too narrow. Grant clusterMonitor or scope tools to a specific DB via listCollections instead.

Write rejected / running in read-only mode

Restart the MCP without --read-only; only do this for the specific fix session.

Альтернативы

MongoDB в сравнении

АльтернативаКогда использоватьКомпромисс
Postgres MCPYou're on Postgres, or considering migrating from MongoRelational — document-style flexibility gone
DBHubYou need one MCP for Mongo + several SQL DBsShallower Mongo feature coverage than the official server

Ещё

Ресурсы

📖 Читать официальный README на GitHub

🐙 Открытые задачи

🔍 Все 400+ MCP-серверов и Skills