MongoDB MCP Server

MongoDB MCP Server

A Model Context Protocol server that provides read-only access to MongoDB databases, enabling AI assistants to directly query and analyze MongoDB data while maintaining data safety.

jonfreeland

Databases
JavaScript
Visit Server

Tools

list_databases

List all databases in the MongoDB server.

list_collections

List all collections in a database. Start here to understand what collections are available before querying.

get_schema

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 }

query

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": "," } }

aggregate

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 - $lookup: Perform left outer joins - $unwind: Deconstruct array fields Unsafe/Blocked Stages: - $out: Write results to collection - $merge: Merge results into collection - $addFields: Add new fields - $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 }} ] }

get_collection_stats

Get detailed statistics about a collection. Returns information about: - Document count and size - Storage metrics - Index sizes and usage - Average document size - Padding factor

get_indexes

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

explain_query

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.

get_distinct_values

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

sample_data

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": "," } }

count_documents

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

find_by_ids

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

geo_query

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

text_search

Perform a full-text search on a collection. Requirements: - Collection must have a text index - Only one text index per collection is allowed Features: - Supports phrases and keywords - Word stemming - Stop words removal - Text score ranking Example: use_mcp_tool with server_name: "mongodb", tool_name: "text_search", arguments: { "collection": "articles", "searchText": "mongodb database", "filter": { "published": true }, "limit": 10, "includeScore": true }

README

MongoDB MCP Server

A Model Context Protocol server that provides read-only access to MongoDB databases through standardized MCP tools and resources.

<a href="https://glama.ai/mcp/servers/cmywezu1sn"> <img width="380" height="200" src="https://glama.ai/mcp/servers/cmywezu1sn/badge" alt="MongoDB Server MCP server" /> </a>

Overview

This MongoDB MCP server enables AI assistants to directly query and analyze MongoDB databases without write access, maintaining data safety while providing powerful data exploration capabilities.

Features

MongoDB Operations

  • Database Exploration: List databases and collections
  • Schema Discovery: Infer collection schemas from sample documents
  • Querying: Execute MongoDB queries with filtering, projection, sorting, and limiting
  • Aggregation: Run read-only aggregation pipelines with safety validation
  • Text Search: Perform full-text search on collections with text indexes
  • Geospatial Queries: Find locations near points, within polygons, or intersecting geometries
  • Document Operations: Count documents, sample random documents, find documents by IDs
  • Data Analysis: Get collection statistics, index information, and query execution plans
  • Performance Insights: Examine query execution plans to optimize performance
  • Data Exploration: Get distinct values, field distributions, and data samples
  • Format Conversion: Export query results as JSON or CSV formats

Enhanced Capabilities

  • Schema Inference: Automatically detect data types and structure from documents
  • Visualization Hints: Intelligent suggestions for data visualization based on result content
  • Safety Validation: Prevents write operations in aggregation pipelines
  • Example-Rich Documentation: Each tool includes detailed examples in its description

Requirements

Environment Variables

  • MONGODB_URI (required): MongoDB connection string with authentication if needed
  • MONGODB_DEFAULT_DATABASE (optional): Default database name when not specified in queries

Prerequisites

  • Network access to MongoDB server
  • Authentication credentials if required by MongoDB instance
  • Appropriate read permissions on target databases

Installation

Building from Source

Install dependencies:

npm install

Build the server:

npm run build

For development with auto-rebuild:

npm run watch

Integration with Claude Desktop

To use with Claude Desktop, add the server configuration:

On MacOS: ~/Library/Application Support/Claude/claude_desktop_config.json On 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"
      }
    }
  }
}

Integration with Claude Web

For Claude Web via the MCP Chrome extension, add configuration to Cline MCP settings:

{
  "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"
      }
    }
  }
}

Integration with Claude Code

To use with Claude Code, use the following commands:

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 

Make sure to replace the placeholders with your actual MongoDB connection string and default database name.

If configured correctly, you should see the following when you run claude:

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

If you run into issues, see the Claude Code documentation.

Security Considerations

  • This server provides read-only access by design
  • Connection strings may contain sensitive authentication information
  • Store connection strings securely in environment variables
  • Use a MongoDB user with read-only permissions

Debugging

Since MCP servers communicate over stdio, debugging can be challenging. Use the MCP Inspector, which is available as a package script:

npm run inspector

The Inspector will provide a URL to access debugging tools in your browser.

Recommended Servers

Claude Code MCP

Claude Code MCP

An implementation of Claude Code as a Model Context Protocol server that enables using Claude's software engineering capabilities (code generation, editing, reviewing, and file operations) through the standardized MCP interface.

Featured
Local
JavaScript
Supabase MCP Server

Supabase MCP Server

A Model Context Protocol (MCP) server that provides programmatic access to the Supabase Management API. This server allows AI models and other clients to manage Supabase projects and organizations through a standardized interface.

Featured
JavaScript
@kazuph/mcp-gmail-gas

@kazuph/mcp-gmail-gas

Model Context Protocol server for Gmail integration. This allows Claude Desktop (or any MCP client) to interact with your Gmail account through Google Apps Script.

Featured
JavaScript
MCP DuckDB Knowledge Graph Memory Server

MCP DuckDB Knowledge Graph Memory Server

A memory server for Claude that stores and retrieves knowledge graph data in DuckDB, enhancing performance and query capabilities for conversations with persistent user information.

Featured
TypeScript
dbt Semantic Layer MCP Server

dbt Semantic Layer MCP Server

A server that enables querying the dbt Semantic Layer through natural language conversations with Claude Desktop and other AI assistants, allowing users to discover metrics, create queries, analyze data, and visualize results.

Featured
TypeScript
Metabase MCP Server

Metabase MCP Server

Enables AI assistants to interact with Metabase databases and dashboards, allowing users to list and execute queries, access data visualizations, and interact with database resources through natural language.

Featured
JavaScript
Airtable MCP Server

Airtable MCP Server

A Model Context Protocol server that provides tools for programmatically managing Airtable bases, tables, fields, and records through Claude Desktop or other MCP clients.

Featured
JavaScript
Linear MCP Server

Linear MCP Server

A Model Context Protocol server that integrates with Linear's issue tracking system, allowing LLMs to create, update, search, and comment on Linear issues through natural language interactions.

Featured
JavaScript
mcp-shodan

mcp-shodan

MCP server for querying the Shodan API and Shodan CVEDB. This server provides tools for IP lookups, device searches, DNS lookups, vulnerability queries, CPE lookups, and more.

Featured
JavaScript
Verodat MCP Server

Verodat MCP Server

An MCP server that integrates Verodat's data management capabilities with AI systems like Claude Desktop, enabling users to manage accounts, workspaces, and datasets, as well as perform AI-powered queries on their data.

Official
Local
TypeScript