/ Diretório / Playground / MongoDB
● Oficial mongodb-js 🔑 Requer sua chave

MongoDB

por 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.

Por que usar

Principais recursos

Demo ao vivo

Como fica na prática

mongodb.replay ▶ pronto
0/0

Instalar

Escolha seu cliente

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

Abra Claude Desktop → Settings → Developer → Edit Config. Reinicie após salvar.

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

Cursor usa o mesmo esquema mcpServers que o Claude Desktop. Config de projeto vence a global.

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

Clique no ícone MCP Servers na barra lateral do Cline, depois "Edit Configuration".

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

Mesmo formato do Claude Desktop. Reinicie o Windsurf para aplicar.

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

O Continue usa um array de objetos de servidor em vez de um map.

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

Adicione em context_servers. Zed recarrega automaticamente ao salvar.

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

Uma linha só. Verifique com claude mcp list. Remova com claude mcp remove.

Casos de uso

Usos do mundo real: MongoDB

Answer business questions with Mongo aggregation pipelines

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

Quando usar: You need counts, funnels, or top-N lists and don't want to learn $group/$lookup syntax.

Pré-requisitos
  • Read-only connection string — Atlas: create a DB user with readAnyDatabase. Self-hosted: user with read role on relevant DBs.
Fluxo
  1. Discover collections
    List databases, then for app_prod list all collections and their approximate document counts.✓ Copiado
    → Collection catalog
  2. Sample and infer schema
    Sample 20 docs from users and orders. Describe the fields and types you see.✓ Copiado
    → 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.✓ Copiado
    → Results table with the pipeline used

Resultado: Business answers with the exact pipeline preserved for re-running.

Armadilhas
  • 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
Combine com: notion

Infer and document a messy collection's actual schema

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

Quando usar: The collection was 'schemaless' for 3 years and nobody knows which fields actually exist.

Fluxo
  1. Sample broadly
    Sample 500 docs from events. For each top-level field, report presence %, type(s), and a sample value.✓ Copiado
    → Field-by-field presence/type matrix
  2. Find schema drift
    Which fields have multiple types across docs? Group by (field, type) and count.✓ Copiado
    → 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.✓ Copiado
    → Usable type definition

Resultado: A documented schema with known quirks — the basis for migrations or a validator.

Armadilhas
  • 500 docs may miss rare but important variants — Sample by time bucket (one per month) to catch legacy shapes
Combine com: filesystem

Audit your Atlas projects for security and cost

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

Quando usar: Quarterly: check which clusters are oversized, which have wide IP allowlists, who has access.

Pré-requisitos
  • Atlas API public+private key — cloud.mongodb.com → Organization Access → API keys; project-scoped
Fluxo
  1. List projects + clusters
    List every project and within each, every cluster with its tier, region, and backup status.✓ Copiado
    → 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.✓ Copiado
    → Risky-access report
  3. Suggest rightsizing
    Any cluster on M30+ with fewer than 10GB used? Recommend downgrades.✓ Copiado
    → Cost-savings list

Resultado: A short remediation list for your security + finance folks.

Armadilhas
  • API key scope too narrow to see every project — Use an Organization-level key in read-only mode rather than a project-level one
Combine com: notion

Propose and execute a one-off data cleanup safely

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

Quando usar: A bug caused bad writes; you need to fix ~10k docs but must not nuke the wrong ones.

Pré-requisitos
  • 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
Fluxo
  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.✓ Copiado
    → 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.✓ Copiado
    → 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.✓ Copiado
    → Counts match expectation; verify query returns 0

Resultado: A clean, auditable fix with counts before and after.

Armadilhas
  • 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
Combine com: filesystem

Suggest missing indexes from slow-query patterns

👤 Backend engineers hunting perf issues ⏱ ~25 min advanced

Quando usar: Your app is slow on Mongo queries; you want a targeted index plan, not a shotgun.

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

Resultado: A single, justifiable index recommendation per slow query — not a wall of them.

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

Combinações

Combine com outros MCPs para 10× de alavancagem

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.✓ Copiado
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.✓ Copiado
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.✓ Copiado

Ferramentas

O que este MCP expõe

FerramentaEntradasQuando chamarCusto
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

Custo e limites

O que custa rodar

Cota de API
Driver: bounded by cluster connection limit. Atlas API: 100 req/min per key.
Tokens por chamada
Find/aggregate: scales with result size; use projections and limits.
Monetário
Free against your existing cluster. Atlas has a free M0 tier for testing.
Dica
Always project only the fields you need; unbounded finds return large docs that chew context and egress.

Segurança

Permissões, segredos, alcance

Escopos mínimos: readAnyDatabase (read-only) or read on specific DBs
Armazenamento de credenciais: MDB_MCP_CONNECTION_STRING for driver; MDB_MCP_API_CLIENT_ID + MDB_MCP_API_CLIENT_SECRET for Atlas
Saída de dados: Driver connects to your cluster; Atlas API to cloud.mongodb.com only
Nunca conceda: dbAdminAnyDatabase userAdminAnyDatabase root

Solução de problemas

Erros comuns e correções

MongoServerError: Authentication failed

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

Verificar: 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.

Verificar: 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.

Alternativas

MongoDB vs. outros

AlternativaQuando usarTroca
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

Mais

Recursos

📖 Leia o README oficial no GitHub

🐙 Ver issues abertas

🔍 Ver todos os 400+ servidores MCP e Skills