MCP Library updated 13 min read

MongoDB MCP Server: AI-Powered NoSQL Database Queries

Query and manage MongoDB databases using natural language. Learn how to explore collections, aggregate data, and analyze documents with AI assistance.

RP

Rajesh Praharaj

Aug 29, 2025 · Updated Dec 27, 2025

MongoDB MCP Server: AI-Powered NoSQL Database Queries

TL;DR - MongoDB MCP Quick Start

Query your MongoDB databases with natural language - Explore, aggregate, and analyze documents.

🆕 2025: MongoDB launched official MCP Server (GA Sept 2025)! Plus Atlas Vector Search, Voyage AI acquisition, and Queryable Encryption 2.0. For an introduction to MCP, see the MCP Introduction guide.

Quick Setup:

{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": ["-y", "mcp-server-mongodb"],
      "env": {
        "MONGODB_URI": "mongodb+srv://user:pass@cluster.mongodb.net/mydb"
      }
    }
  }
}

What you can do:

  • 🔍 Query: Find documents with filters
  • 📊 Aggregate: Complex data analysis
  • 📋 Explore: Discover collections and schemas
  • 📈 Stats: Collection and index info
  • 🎯 Sample: Random document samples

Example conversation:

You: Show me users who signed up this month with their order count

Claude: I'll query users and aggregate their orders...

        | User         | Email              | Signups   | Orders |
        |--------------|--------------------| ----------|--------|
        | Alice Brown  | alice@example.com  | Dec 15    | 5      |
        | Bob Smith    | bob@example.com    | Dec 18    | 3      |
        | Carol Jones  | carol@example.com  | Dec 20    | 1      |
        
        Found 47 users who signed up this month.

⚠️ Security: Always use a database user with minimal required permissions.

🤖 Official MCP: MongoDB’s official MCP Server works with Claude Desktop, Cursor, VS Code Copilot, and Windsurf.


PostgreSQL vs MongoDB MCP

When to use each database MCP:

MongoDB MCPPostgreSQL MCP
Document databasesRelational databases
Flexible schemasFixed schemas
Aggregation pipelinesSQL queries
Nested documentsJOINs across tables
MongoDB/AtlasPostgreSQL/Aurora

Prerequisites

1. MongoDB Access

You need either:

  • MongoDB Atlas cluster (cloud)
  • Self-hosted MongoDB instance
  • Local MongoDB for development

2. Connection String

Format: mongodb+srv://user:password@cluster.mongodb.net/database

For Atlas:

  1. Go to your cluster in Atlas
  2. Click Connect
  3. Choose Drivers
  4. Copy the connection string
  5. Replace <password> with actual password

For Local:

mongodb://localhost:27017/mydb

For Replica Set:

mongodb://host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplSet

3. Database User

Create a user with minimal permissions:

// Read-only user (recommended)
db.createUser({
  user: "mcp_reader",
  pwd: "secure_password",
  roles: [
    { role: "read", db: "mydb" }
  ]
})

// Read-write user (if needed)
db.createUser({
  user: "mcp_writer",
  pwd: "secure_password", 
  roles: [
    { role: "readWrite", db: "mydb" }
  ]
})

Installation & Configuration

Basic Setup

Add to claude_desktop_config.json:

{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": ["-y", "mcp-server-mongodb"],
      "env": {
        "MONGODB_URI": "mongodb+srv://user:pass@cluster.mongodb.net/mydb"
      }
    }
  }
}

Local Development

{
  "mcpServers": {
    "mongodb-local": {
      "command": "npx",
      "args": ["-y", "mcp-server-mongodb"],
      "env": {
        "MONGODB_URI": "mongodb://localhost:27017/myapp"
      }
    }
  }
}

Multiple Databases

{
  "mcpServers": {
    "mongodb-prod": {
      "command": "npx",
      "args": ["-y", "mcp-server-mongodb"],
      "env": {
        "MONGODB_URI": "mongodb+srv://reader:pass@prod.mongodb.net/app"
      }
    },
    "mongodb-analytics": {
      "command": "npx",
      "args": ["-y", "mcp-server-mongodb"],
      "env": {
        "MONGODB_URI": "mongodb+srv://reader:pass@analytics.mongodb.net/data"
      }
    }
  }
}

Verify Installation

Restart your AI client and test:

You: What collections are in the database?

Claude: Here are your collections:

        | Collection | Documents | Size    |
        |------------|-----------|---------|
        | users      | 15,432    | 12 MB   |
        | orders     | 89,012    | 156 MB  |
        | products   | 2,847     | 4 MB    |
        | sessions   | 45,231    | 23 MB   |

Available Tools

Collection & Schema

ToolDescriptionExample Prompt
list_collectionsShow all collections”What collections exist?”
get_schemaInfer collection schema”Describe the users schema”
get_indexesList collection indexes”What indexes are on orders?”

Query Operations

ToolDescriptionExample Prompt
findQuery documents”Find active premium users”
findOneGet single document”Show order #12345”
countCount documents”How many orders today?”
distinctUnique values”What product categories exist?”

Aggregation

ToolDescriptionExample Prompt
aggregateComplex pipeline”Total revenue by month”
sampleRandom documents”Show 5 random users”

Stats

ToolDescriptionExample Prompt
collection_statsCollection metrics”Stats for orders collection”
explainQuery explanation”Explain this query’s performance”

Practical Workflows

Workflow 1: Data Exploration

Understand your data structure. For more on AI-assisted analysis, see the AI-Powered Workflows guide.

You: Explore the users collection and describe its schema

Claude: Analyzing users collection...

        **Collection: users**
        Documents: 15,432 | Size: 12 MB
        
        **Schema (inferred from 100 samples):**
        
        | Field        | Type     | Present | Example               |
        |--------------|----------|---------|----------------------|
        | _id          | ObjectId | 100%    | 507f1f77bcf86cd799439011 |
        | email        | String   | 100%    | "user@example.com"   |
        | name         | String   | 100%    | "John Smith"         |
        | createdAt    | Date     | 100%    | ISODate("2024-12-01")|
        | profile      | Object   | 95%     | { bio: "...", ... }  |
        | profile.bio  | String   | 80%     | "Software engineer"  |
        | profile.avatar| String  | 60%     | "https://..."        |
        | plan         | String   | 100%    | "premium", "free"    |
        | tags         | Array    | 45%     | ["developer", "beta"]|
        
        **Plan Distribution:**
        - premium: 3,421 (22%)
        - basic: 8,234 (53%)
        - free: 3,777 (25%)
        
        **Indexes:**
        - _id (unique)
        - email (unique)
        - createdAt

Workflow 2: Business Analytics

Answer business questions:

You: What's our monthly revenue trend and average order value?

Claude: Running aggregation on orders collection...

        **Monthly Revenue (Last 6 Months)**
        
        | Month    | Orders | Revenue    | AOV    | Growth |
        |----------|--------|------------|--------|--------|
        | Dec 2024 | 2,345  | $234,560   | $100   | +12%   |
        | Nov 2024 | 2,189  | $209,450   | $96    | +8%    |
        | Oct 2024 | 2,034  | $193,890   | $95    | +5%    |
        | Sep 2024 | 1,956  | $184,720   | $94    | +3%    |
        | Aug 2024 | 1,890  | $179,230   | $95    | +7%    |
        | Jul 2024 | 1,756  | $167,340   | $95    | -      |
        
        **Insights:**
        - Revenue up 40% over 6 months
        - Average order value steady at ~$95-100
        - December showing strong holiday performance
        
        **Aggregation Used:**
        ```javascript
        db.orders.aggregate([
          { $match: { status: "completed" } },
          { $group: {
              _id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } },
              revenue: { $sum: "$total" },
              count: { $sum: 1 }
          }},
          { $sort: { _id: -1 } },
          { $limit: 6 }
        ])

### Workflow 3: User Behavior Analysis

Understand user patterns:

```text
You: Show me power users - those with more than 10 orders 
     in the last month, with their activity

Claude: Finding power users...

        **Power Users (10+ orders in December)**
        
        | User          | Orders | Total Spent | Last Order |
        |---------------|--------|-------------|------------|
        | alice@co.com  | 34     | $3,456      | Dec 24     |
        | bob@inc.com   | 28     | $2,890      | Dec 23     |
        | carol@web.io  | 19     | $1,923      | Dec 24     |
        | dave@tech.co  | 15     | $1,567      | Dec 22     |
        | eve@shop.com  | 12     | $1,234      | Dec 21     |
        
        **Power User Profile:**
        - 5 users qualify (0.03% of total)
        - Average: 21.6 orders/month
        - Average spend: $2,214/month
        - Most common plan: Premium (100%)
        
        **Common Characteristics:**
        - All are on premium plan
        - 80% signed up in 2023 or earlier
        - Frequent categories: Electronics, Software

Workflow 4: Data Quality Check

Find data issues:

You: Check the orders collection for data quality issues

Claude: Analyzing orders collection for data quality...

        **Data Quality Report**
        
        ⚠️ **Issues Found:**
        
        1. **Missing Fields:**
           | Field       | Missing | % of Total |
           |-------------|---------|------------|
           | shippingAddress | 234 | 0.3%    |
           | customerEmail   | 12  | 0.01%   |
           
        2. **Invalid Values:**
           - 45 orders with negative totals
           - 23 orders with future dates
           - 7 orders with invalid status
        
        3. **Duplicates:**
           - 3 potential duplicate orders (same user, items, within 1 min)
        
        4. **Inconsistencies:**
           - Status "shipped" but no trackingNumber: 89 orders
           - Status "delivered" but no deliveryDate: 34 orders
        
        ✅ **Healthy (99.7%):**
        - 88,645 orders pass all checks
        
        **Recommendations:**
        1. Add validation for order totals
        2. Add required field for shippingAddress
        3. Review the 3 potential duplicates

You: Show me those orders with negative totals

Claude: Orders with negative totals:

        | Order ID     | Total   | Date     | User         |
        |--------------|---------|----------|--------------|
        | 507f1f77...  | -$45.00 | Dec 20   | user1@...    |
        | 507f1f78...  | -$12.50 | Dec 21   | user2@...    |
        ...
        
        **Pattern:** 43 of 45 appear to be refunds incorrectly 
        stored as orders. Consider using a separate "refunds" field.

Workflow 5: Performance Investigation

Analyze slow queries. For more on building AI-powered applications, see the Building Your First AI Application guide.

You: Which queries on the orders collection might be slow?

Claude: Analyzing orders collection performance...

        **Index Analysis:**
        
        Existing indexes:
        | Index Name    | Fields              | Usage |
        |---------------|---------------------|-------|
        | _id           | _id                 | High  |
        | customer_idx  | customerId          | High  |
        | date_idx      | createdAt           | Med   |
        
        **Potential Issues:**
        
        ⚠️ **Missing Indexes for Common Queries:**
        
        1. **Status queries** - No index on `status`
           - Queries like `{ status: "pending" }` do full scan
           - Recommendation: `{ status: 1 }`
           
        2. **Combined filters** - No compound index
           - Queries like `{ customerId, status }` partially use index
           - Recommendation: `{ customerId: 1, status: 1 }`
        
        3. **Date range + customer**
           - Common query: Find customer's orders in date range
           - Missing compound index
           - Recommendation: `{ customerId: 1, createdAt: -1 }`
        
        **Index Creation Commands:**
        ```javascript
        db.orders.createIndex({ status: 1 })
        db.orders.createIndex({ customerId: 1, status: 1 })
        db.orders.createIndex({ customerId: 1, createdAt: -1 })

---

## Example Prompts

### Data Discovery

```text
# Collections
"What collections are in this database?"
"Show me collection sizes and document counts"
"Which collection is largest?"

# Schema
"Describe the structure of the users collection"
"What fields are in the products documents?"
"Are there any nested objects in orders?"

# Sampling
"Show me 5 random documents from users"
"What does a typical order look like?"
"Show examples of each product category"

Querying

# Simple queries
"Find all users with plan='premium'"
"Show orders from today"
"Get products with price over $100"

# Complex filters
"Find users who signed up this month and have no orders"
"Show orders that are pending and over $100"
"Get products that are out of stock and were bestsellers"

# Counts and existence
"How many active users are there?"
"Are there any orders without shipping addresses?"
"Count products by category"

Aggregations

# Grouping
"Total sales by product category"
"Average order value by customer segment"
"Count users by signup month"

# Time series
"Show daily order count for December"
"Revenue trend over the last 6 months"
"Average response time by hour of day"

# Advanced
"Top 10 customers by lifetime value"
"Products often bought together"
"User retention by cohort"

Data Quality

# Missing data
"Find documents with missing email fields"
"Which orders have no shipping address?"
"Count products without descriptions"

# Validation
"Are there any invalid phone numbers?"
"Find orders with negative totals"
"Check for duplicate user emails"

# Consistency
"Are all referenced products valid?"
"Find orphaned order items"
"Check for status inconsistencies"

Combining with Other MCPs

MongoDB + Filesystem

Export data locally:

You: Export the monthly sales report to a JSON file

Claude: [Uses MongoDB to aggregate data]
        [Uses Filesystem to save file]
        
        Exported to: /reports/sales-december-2024.json
        - 12 months of data
        - Revenue, order counts, AOV
        - 24KB file size

MongoDB + Slack

Share insights with team:

You: Calculate today's sales and post to #daily-metrics

Claude: [Uses MongoDB to query today's orders]
        [Uses Slack to post]
        
        Posted to #daily-metrics:
        
        📊 **Daily Metrics - Dec 24**
        - Orders: 234
        - Revenue: $23,456
        - AOV: $100.24
        - vs yesterday: +12%

MongoDB + Memory

Remember database context:

You: Learn the structure of this database for future queries

Claude: [Uses MongoDB to explore all collections]
        [Uses Memory to store schema]
        
        Memorized database structure:
        - 8 collections documented
        - Schema patterns stored
        - Relationship map created
        
        I'll use this context for faster queries!

Troubleshooting

Issue: “Connection failed”

Solutions:

CauseSolution
Wrong connection stringVerify format and credentials
Network/firewallCheck IP allowlist (Atlas)
AuthenticationVerify username/password
Database nameCheck database exists

Issue: “Not authorized”

Solutions:

  • Verify user has read permissions
  • Check user roles in MongoDB
  • Atlas: Verify database user, not account login

Issue: “Query timeout”

Solutions:

  • Add indexes for filtered fields
  • Use projections to limit returned fields
  • Add query limits
  • Consider query optimization

Security Best Practices

Connection Security

✅ Do❌ Don’t
Use SRV connection stringsHardcode in plain text
Enable TLSDisable SSL
Use dedicated MCP userUse admin credentials
Limit IP allowlistAllow 0.0.0.0/0

For more on AI security best practices, see the Understanding AI Safety, Ethics, and Limitations guide.

User Permissions

Read-Only (Recommended):

{ role: "read", db: "mydb" }

Specific Collection:

{
  role: "read",
  db: "mydb",
  collection: "selected_collection"
}

ServerComplements MongoDB By…
PostgreSQL MCPRelational data
Filesystem MCPExporting data
Slack MCPSharing insights
Memory MCPRemembering schemas

Summary

MongoDB MCP Server enables natural language NoSQL queries:

  • Find documents with complex filters
  • Aggregations for analytics
  • Schema discovery for flexible data
  • Data quality checks
  • Performance analysis
  • Official MCP (2025) - MongoDB’s official server

2025 MongoDB AI Features:

  • Official MCP Server (GA Sept 2025)
  • Enterprise auth and remote deployment
  • Atlas Vector Search - semantic search & RAG
  • Voyage AI acquisition - better embeddings
  • Queryable Encryption 2.0 - privacy-first AI

Best use cases:

  • Data exploration
  • Business analytics
  • User behavior analysis
  • Data quality audits
  • Performance investigations

Security checklist:

  • ☐ Create dedicated read-only user
  • ☐ Use secure connection strings
  • ☐ Enable TLS
  • ☐ Limit IP allowlist
  • ☐ Never expose credentials

🎉 Phase 4 Complete! Continue to Phase 5 for advanced topics.


Questions about MongoDB MCP? Check the MongoDB MCP Server docs or the MCP Registry.

Was this page helpful?

Let us know if you found what you were looking for.