Skip to main content
Glama
MongoDB MCP Server

MongoDB MCP Server

by jonfreeland

MongoDB MCP 서버

표준화된 MCP 도구와 리소스를 통해 MongoDB 데이터베이스에 대한 읽기 전용 액세스를 제공하는 모델 컨텍스트 프로토콜 서버입니다.

개요

이 MongoDB MCP 서버를 사용하면 AI 도우미가 쓰기 액세스 권한 없이 MongoDB 데이터베이스를 직접 쿼리하고 분석할 수 있으므로 강력한 데이터 탐색 기능을 제공하는 동시에 데이터 안전성을 유지할 수 있습니다.

Related MCP server: MongoDB MCP Server for LLMs

특징

MongoDB 운영

  • 데이터베이스 탐색 : 데이터베이스 및 컬렉션 나열

  • 스키마 검색 : 샘플 문서에서 컬렉션 스키마 추론

  • 쿼리 : 필터링, 프로젝션, 정렬 및 제한을 사용하여 MongoDB 쿼리 실행

  • 집계 : 안전 검증을 통해 읽기 전용 집계 파이프라인을 실행합니다.

  • 텍스트 검색 : 텍스트 인덱스가 있는 컬렉션에서 전체 텍스트 검색을 수행합니다.

  • 지리공간 쿼리 : 점 근처, 폴리곤 내부 또는 교차하는 지오메트리 내의 위치 찾기

  • 문서 작업 : 문서 계산, 무작위 문서 샘플링, ID로 문서 찾기

  • 데이터 분석 : 수집 통계, 인덱스 정보 및 쿼리 실행 계획을 가져옵니다.

  • 성능 통찰력 : 성능 최적화를 위한 쿼리 실행 계획 검토

  • 데이터 탐색 : 고유한 값, 필드 분포 및 데이터 샘플 가져오기

  • 형식 변환 : 쿼리 결과를 JSON 또는 CSV 형식으로 내보내기

향상된 기능

  • 스키마 추론 : 문서에서 데이터 유형과 구조를 자동으로 감지합니다.

  • 시각화 힌트 : 결과 내용을 기반으로 한 데이터 시각화를 위한 지능형 제안

  • 안전성 검증 : 집계 파이프라인에서 쓰기 작업을 방지합니다.

  • 풍부한 예제 문서 : 각 도구에는 설명에 자세한 예제가 포함되어 있습니다.

요구 사항

환경 변수

  • MONGODB_URI (필수): 필요한 경우 인증을 포함한 MongoDB 연결 문자열

  • MONGODB_DEFAULT_DATABASE (선택 사항): 쿼리에 지정되지 않은 경우 기본 데이터베이스 이름

필수 조건

  • MongoDB 서버에 대한 네트워크 액세스

  • MongoDB 인스턴스에 필요한 경우 인증 자격 증명

  • 대상 데이터베이스에 대한 적절한 읽기 권한

설치

소스에서 빌드

종속성 설치:

지엑스피1

서버를 빌드하세요:

npm run build

자동 재빌드를 사용한 개발의 경우:

npm run watch

Claude Desktop과 통합

Claude Desktop과 함께 사용하려면 서버 구성을 추가하세요.

MacOS의 경우: ~/Library/Application Support/Claude/claude_desktop_config.json Windows의 경우: %APPDATA%/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "mongodb": {
      "command": "/path/to/mongodb-server/build/index.js",
      "env": {
        "MONGODB_URI": "mongodb://username:password@hostname:port/database",
        "MONGODB_DEFAULT_DATABASE": "your_default_db"
      }
    }
  }
}

Claude Web과 통합

MCP Chrome 확장 프로그램을 통해 Claude Web을 사용하는 경우 Cline MCP 설정에 구성을 추가합니다.

{
  "mcpServers": {
    "mongodb": {
      "command": "node",
      "args": ["/path/to/mongodb-server/build/index.js"],
      "env": {
        "MONGODB_URI": "mongodb://username:password@hostname:port/database",
        "MONGODB_DEFAULT_DATABASE": "your_default_db"
      }
    }
  }
}

Claude Code와의 통합

Claude Code와 함께 사용하려면 다음 명령을 사용하세요.

cd /path/to/my/project
claude mcp add mongo-server /path/to/mongodb-mcp/build/index.js -e "MONGODB_URI=mongodb://user@password:27017/dbname?authSource=authDbName" -e MONGO_DEFAULT_DATABASE=dbname 

플레이스홀더를 실제 MongoDB 연결 문자열과 기본 데이터베이스 이름으로 바꿔야 합니다.

올바르게 구성한 경우 claude 실행하면 다음이 표시됩니다.

╭───────────────────────────────────────────────────────╮
│ ✻ Welcome to Claude Code research preview!            │
│                                                       │
│   /help for help                                      │
│                                                       │
│   cwd: <path-to-project-directory>                    │
│                                                       │
│   ─────────────────────────────────────────────────── │
│                                                       │
│   MCP Servers:                                        │
│                                                       │
│   • mongo-server                            connected │
╰───────────────────────────────────────────────────────╯

문제가 발생하면 Claude Code 설명서를 참조하세요.

보안 고려 사항

  • 이 서버는 설계상 읽기 전용 액세스를 제공합니다.

  • 연결 문자열에는 중요한 인증 정보가 포함될 수 있습니다.

  • 환경 변수에 연결 문자열을 안전하게 저장합니다.

  • 읽기 전용 권한이 있는 MongoDB 사용자 사용

디버깅

MCP 서버는 stdio를 통해 통신하므로 디버깅이 어려울 수 있습니다. 패키지 스크립트로 제공되는 MCP Inspector를 사용하세요.

npm run inspector

검사기는 브라우저에서 디버깅 도구에 액세스할 수 있는 URL을 제공합니다.

Available Tools

14 tools
aggregateA

Execute a read-only aggregation pipeline on a collection.

Supported Stages:

  • $match: Filter documents

  • $group: Group documents by a key

  • $sort: Sort documents

  • $project: Shape the output

  • $addFields - Include additional or calculated fields

  • $lookup: Perform left outer joins

  • $unwind: Deconstruct array fields

Unsafe/Blocked Stages:

  • $out: Write results to collection

  • $merge: Merge results into collection

  • $set: Set field values

  • $unset: Remove fields

  • $replaceRoot: Replace document structure

  • $replaceWith: Replace document

Example - User Statistics by Role: use_mcp_tool with server_name: "mongodb", tool_name: "aggregate", arguments: { "collection": "users", "pipeline": [ { "$match": { "active": true } }, { "$group": { "_id": "$role", "count": { "$sum": 1 }, "avgAge": { "$avg": "$age" } }}, { "$sort": { "count": -1 } } ], "limit": 100 }

Example - Posts with Author Details: use_mcp_tool with server_name: "mongodb", tool_name: "aggregate", arguments: { "collection": "posts", "pipeline": [ { "$match": { "published": true } }, { "$lookup": { "from": "users", "localField": "authorId", "foreignField": "_id", "as": "author" }}, { "$unwind": "$author" }, { "$project": { "title": 1, "authorName": "$author.name", "publishDate": 1 }} ] }

Inputs: collection (required), pipeline (required), database, limit.

count_documentsA

Count documents in a collection that match a filter.

Benefits:

  • More efficient than retrieving full documents

  • Good for understanding data volume

  • Can help planning query strategies

  • Optimize pagination implementation

Example: use_mcp_tool with server_name: "mongodb", tool_name: "count_documents", arguments: { "collection": "users", "filter": { "active": true, "age": { "$gte": 21 } } }

Inputs: collection (required), database, filter.

explain_queryA

Get the execution plan for a query.

Helps understand:

  • How MongoDB will execute the query

  • Which indexes will be used

  • Number of documents examined

  • Execution stages and timing

Use this to optimize slow queries.

Inputs: collection (required), filter (required), database, projection, +1 more.

find_by_idsA

Find multiple documents by their IDs in a single request.

Advantages:

  • More efficient than multiple single document lookups

  • Preserves ID order in results when possible

  • Can filter specific fields with projection

  • Handles both string and ObjectId identifiers

Example: use_mcp_tool with server_name: "mongodb", tool_name: "find_by_ids", arguments: { "collection": "products", "ids": ["5f8d0f3c", "5f8d0f3d", "5f8d0f3e"], "idField": "_id", "projection": { "name": 1, "price": 1 } }

Inputs: collection (required), ids (required), database, idField, +1 more.

geo_queryA

Execute geospatial queries on a MongoDB collection.

Supports:

  • Finding points near a location

  • Finding documents within a polygon, circle, or box

  • Calculating distances between points

  • GeoJSON and legacy coordinate pair formats

Requirements:

  • Collection must have a geospatial index (2dsphere recommended)

  • Coordinates should follow MongoDB conventions (longitude first, then latitude)

Examples:

  1. Find locations near a point (2 miles radius): use_mcp_tool with server_name: "mongodb", tool_name: "geo_query", arguments: { "collection": "restaurants", "operation": "near", "point": [-73.9667, 40.78], "maxDistance": 3218.69, // 2 miles in meters "distanceField": "distance" }

  2. Find locations within a polygon: use_mcp_tool with server_name: "mongodb", tool_name: "geo_query", arguments: { "collection": "properties", "operation": "geoWithin", "geometry": { "type": "Polygon", "coordinates": [ [[-73.958, 40.8], [-73.94, 40.79], [-73.95, 40.76], [-73.97, 40.76], [-73.958, 40.8]] ] } }

Inputs: collection (required), operation (required), database, locationField, +8 more.

get_collection_statsC

Get detailed statistics about a collection.

Returns information about:

  • Document count and size

  • Storage metrics

  • Index sizes and usage

  • Average document size

  • Padding factor

Inputs: collection (required), database.

get_distinct_valuesA

Get distinct values for a field in a collection.

Useful for:

  • Understanding data distribution

  • Finding unique categories

  • Data quality checks

  • Identifying outliers

Example: use_mcp_tool with server_name: "mongodb", tool_name: "get_distinct_values", arguments: { "collection": "users", "field": "role", "filter": { "active": true } }

Inputs: collection (required), field (required), database, filter.

get_indexesB

Get information about indexes on a collection.

Returns details about:

  • Index names and fields

  • Index types (single field, compound, text, etc.)

  • Index sizes

  • Index options

  • Usage statistics

Inputs: collection (required), database.

get_schemaA

Infer schema from a collection by analyzing sample documents.

Best Practice: Use this before querying to understand collection structure.

Example: use_mcp_tool with server_name: "mongodb", tool_name: "get_schema", arguments: { "collection": "users", "sampleSize": 100 }

Inputs: collection (required), database, sampleSize.

list_collectionsA

List all collections in a database.

Start here to understand what collections are available before querying.

Inputs: database.

list_databasesB

List all databases in the MongoDB server.

Inputs: no named parameters.

queryA

Execute a read-only query on a collection using MongoDB query syntax.

Supports both JSON and CSV output formats:

  • Use outputFormat="json" for standard JSON (default)

  • Use outputFormat="csv" for comma-separated values export

Best Practices:

  • Use projections to fetch only needed fields

  • Add limits for large collections

  • Use sort for consistent ordering

Example - Standard Query: use_mcp_tool with server_name: "mongodb", tool_name: "query", arguments: { "collection": "users", "filter": { "age": { "$gte": 21 } }, "projection": { "name": 1, "email": 1 }, "sort": { "name": 1 }, "limit": 100 }

Example - CSV Export: use_mcp_tool with server_name: "mongodb", tool_name: "query", arguments: { "collection": "users", "filter": { "active": true }, "outputFormat": "csv", "formatOptions": { "includeHeaders": true, "delimiter": "," } }

Inputs: collection (required), filter (required), database, projection, +4 more.

sample_dataA

Get a random sample of documents from a collection.

Supports both JSON and CSV output formats:

  • Use outputFormat="json" for standard JSON (default)

  • Use outputFormat="csv" for comma-separated values export

Useful for:

  • Exploratory data analysis

  • Testing with representative data

  • Understanding data distribution

  • Performance testing with realistic data subsets

Example - JSON Sample: use_mcp_tool with server_name: "mongodb", tool_name: "sample_data", arguments: { "collection": "users", "size": 50 }

Example - CSV Export: use_mcp_tool with server_name: "mongodb", tool_name: "sample_data", arguments: { "collection": "users", "size": 100, "outputFormat": "csv", "formatOptions": { "includeHeaders": true, "delimiter": "," } }

Inputs: collection (required), database, size, outputFormat, +1 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A3.7/5.0

    Scored across 14 tools

    Disambiguation4/5

    Most tools have distinct purposes, such as aggregate for complex pipelines, query for basic queries, and geo_query for spatial operations. However, query and sample_data both retrieve documents with overlapping functionality, and get_schema might be confused with get_collection_stats for understanding collection structure, leading to some potential confusion.

    Naming Consistency4/5

    The naming follows a consistent verb_noun pattern throughout, like count_documents, explain_query, and get_indexes. There are minor deviations with list_collections and list_databases using 'list' instead of 'get', but overall the pattern is clear and predictable.

    Tool Count5/5

    With 14 tools, this is well-scoped for a MongoDB server, covering a comprehensive range of read-only operations from basic queries to advanced analytics. Each tool serves a specific purpose, such as aggregation, indexing, geospatial queries, and schema analysis, without feeling bloated or incomplete.

    Completeness5/5

    The tool set provides complete coverage for read-only MongoDB operations, including querying, aggregation, indexing, geospatial queries, text search, and metadata inspection. There are no obvious gaps; it supports everything from data retrieval to performance optimization and schema exploration for the domain.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server that enables LLMs to interact directly with MongoDB databases, allowing users to query collections, inspect schemas, and manage data through natural language.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server that enables LLMs to interact directly with MongoDB databases, allowing users to query collections, inspect schemas, and manage data through natural language.
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol (MCP) server for MongoDB operations, enabling AI assistants to interact with MongoDB databases through a standardized interface.
      6
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      A read-only MongoDB MCP server designed for serverless deployment on Vercel, providing secure, limited access to MongoDB databases for AI assistants.
      1
      -