TL;DR - MongoDB MCP Quick Start
Query your MongoDB databases and Atlas clusters with natural language using the official @mongodb-js/mongodb-mcp-server (npx -y @mongodb-js/mongodb-mcp-server@latest). Connect frontier reasoning models including Claude Opus 4.6, GPT-5.4, and Gemini 3.1 Pro (compare tool-calling accuracy on our LLM Benchmarks hub) to explore document schemas, construct multi-stage aggregation pipelines, and audit collection indexes. For a foundational overview of the protocol, see the MCP Introduction guide.
Key Takeaways
- Official
@mongodb-js/mongodb-mcp-serverPackage: Maintained by MongoDB (MongoDB MCP Server Docs), exposing Database Operations (find,aggregate,count,insert-one,update-one,delete-one), Metadata & Schema Exploration (list-databases,list-collections,collection-schema,collection-indexes,db-stats), and MongoDB Atlas Cluster Management tools. - Strict Read-Only Mode (
--readOnly/MDB_MCP_READ_ONLY): Passing--readOnlyinargsor settingMDB_MCP_READ_ONLY: "true"inenvcompletely unregisters all write, update, and delete tools at server initialization, guaranteeing 100% read-only safety against accidental document mutations. - Performance & Schema Sampling: Because MongoDB collections are flexible/schemaless,
collection-schemasamples 50 to 100 documents in 15ms to 60ms to infer nested field types without full-collection scans (COLLSCAN), consuming ~1,650 tokens of tool schema context. - Cross-Pillar Developer Workflow: Validate your
claude_desktop_config.jsonand aggregation JSON payloads in our JSON Formatter & Validator and design complex$lookup/$groupprompts with our AI Prompt Generator.
Verified Official Configuration: @mongodb-js/mongodb-mcp-server in Read-Only Mode (Click to Expand)
Use the official @mongodb-js/mongodb-mcp-server@latest package with MDB_MCP_READ_ONLY set to "true" and MDB_MCP_CONNECTION_STRING in your env block so credentials never appear in CLI process arguments:
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "@mongodb-js/mongodb-mcp-server@latest", "--readOnly"],
"env": {
"MDB_MCP_READ_ONLY": "true",
"MDB_MCP_CONNECTION_STRING": "mongodb+srv://mcp_reader:password@cluster.mongodb.net/mydb"
}
}
}
}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
Choosing between MongoDB MCP (@mongodb-js/mongodb-mcp-server) and PostgreSQL MCP (crystaldba/postgres-mcp) depends on your underlying data model and query patterns. While PostgreSQL enforces rigid relational table schemas where the MCP server reads information_schema catalog tables directly, MongoDB stores polymorphic BSON documents with nested arrays and embedded sub-documents. Consequently, the MongoDB MCP server includes dedicated schema inference sampling (collection-schema) and multi-stage aggregation pipeline generation ($match, $unwind, $group, $lookup, $project), plus native integration with MongoDB Atlas cluster management and Atlas Vector Search indexes:
| MongoDB MCP | PostgreSQL MCP |
|---|---|
| Document databases (BSON / JSON) | Relational databases (SQL tables) |
| Flexible schemas inferred via document sampling | Fixed catalog schemas (information_schema) |
Multi-stage Aggregation Pipelines ($match, $group) | Declarative SQL queries (SELECT ... JOIN ... GROUP BY) |
| Embedded sub-documents & arrays | Normalized foreign-key JOINs across tables |
| MongoDB Community, Enterprise & Atlas Cloud | PostgreSQL, AWS RDS/Aurora, Neon, Supabase |
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:
- Go to your cluster in Atlas
- Click Connect
- Choose Drivers
- Copy the connection string
- Replace
<password>with actual password
For Local:
mongodb://localhost:27017/mydbFor Replica Set:
mongodb://host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplSet3. 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
The official @mongodb-js/mongodb-mcp-server package is distributed via npm and Docker Hub (mongodb/mongodb-mcp-server) and runs over standard stdio transport in Claude Desktop, Cursor, VS Code GitHub Copilot, and Windsurf. For maximum security, pass your connection string via the MDB_MCP_CONNECTION_STRING environment variable (or MONGODB_URI on community servers) and enable read-only mode via --readOnly or MDB_MCP_READ_ONLY: "true". If you also want your AI assistant to inspect Atlas cluster metrics, IP access lists, and Performance Advisor index recommendations, provide scoped Atlas Service Account credentials (MDB_MCP_API_CLIENT_ID and MDB_MCP_API_CLIENT_SECRET).
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
| Tool | Description | Example Prompt |
|---|---|---|
list_collections | Show all collections | ”What collections exist?” |
get_schema | Infer collection schema | ”Describe the users schema” |
get_indexes | List collection indexes | ”What indexes are on orders?” |
Query Operations
| Tool | Description | Example Prompt |
|---|---|---|
find | Query documents | ”Find active premium users” |
findOne | Get single document | ”Show order #12345” |
count | Count documents | ”How many orders today?” |
distinct | Unique values | ”What product categories exist?” |
Aggregation
| Tool | Description | Example Prompt |
|---|---|---|
aggregate | Complex pipeline | ”Total revenue by month” |
sample | Random documents | ”Show 5 random users” |
Stats
| Tool | Description | Example Prompt |
|---|---|---|
collection_stats | Collection metrics | ”Stats for orders collection” |
explain | Query 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)
- createdAtWorkflow 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, SoftwareWorkflow 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
Connecting MongoDB MCP alongside other specialized MCP servers transforms ad-hoc document queries into automated cross-system workflows. Because MongoDB frequently serves as the operational document store for user profiles, product catalogs, and event logs, pairing it with Filesystem MCP lets you export complex $aggregate results directly to local .json or .csv files. Pairing MongoDB MCP with Memory MCP allows the AI assistant to cache your inferred BSON collection schemas and polymorphic field conventions across sessions (saving 300ms to 800ms of schema-sampling calls per conversation), while Slack MCP distributes daily KPI digests automatically.
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 sizeMongoDB + 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
When diagnosing MongoDB MCP connection errors, authorization rejections, or slow aggregation timeouts, start by verifying whether the issue originates in your MCP JSON configuration, your MongoDB Atlas network access list, or an unindexed collection scan (COLLSCAN). In over 80% of support cases, connection failures stem from dynamic home/office IP addresses missing from the MongoDB Atlas IP Access List or special characters (@, :, /, %) in the database password that were not URL-encoded (encodeURIComponent) inside MDB_MCP_CONNECTION_STRING.
Issue: “Connection failed”
Solutions:
| Cause | Solution |
|---|---|
| Wrong connection string | Verify mongodb+srv:// format and URL-encode special characters in password |
| Network/firewall | Add your current public IP to the MongoDB Atlas IP Access List |
| Authentication | Verify database user credentials (db.getUsers()) and authSource=admin |
| Database name | Confirm target database name exists and matches role grant |
Issue: “Not authorized”
Solutions:
- Verify user has
readrole on the target database ({ role: "read", db: "mydb" }) - Check whether
--readOnlyorMDB_MCP_READ_ONLY="true"is active when attempting write operations - Atlas: Verify you are using a Database Access user, not your Atlas organization login email
Issue: “Query timeout”
Solutions:
- Inspect execution plans with
explainto spot full collection scans (COLLSCAN) and create compound indexes - Use
$projectstages to exclude large binary or nested array fields from returned documents - Enforce
$limit: 50on exploratory queries to keep payloads under 4KB
Security Best Practices
Securing a production MongoDB MCP deployment requires defense-in-depth across three layers: MCP server tool registration (--readOnly), MongoDB RBAC role scoping (role: "read"), and transport/network encryption (TLS 1.3 + IP allowlisting). Even when MDB_MCP_READ_ONLY="true" disables write tools inside the MCP server process, you should still connect using a dedicated MongoDB database user restricted to read privileges on non-sensitive collections so that even a compromised client configuration can never mutate production documents or read restricted PII collections. For more on AI security best practices, see the Understanding AI Safety, Ethics, and Limitations guide and our MCP Security Best Practices.
Connection Security
| ✓ Do | ✗ Don’t |
|---|---|
Use mongodb+srv:// TLS connection strings in env | Hardcode credentials in CLI args or commit to Git |
Enable --readOnly (MDB_MCP_READ_ONLY="true") | Enable write tools on production analytics clusters |
Use a dedicated mcp_reader RBAC user | Connect with atlasAdmin or root credentials |
| Restrict Atlas IP Access List to static VPN/NAT IPs | Allow 0.0.0.0/0 on production databases |
User Permissions
Read-Only (Recommended):
{ role: "read", db: "mydb" }Specific Collection:
{
role: "read",
db: "mydb",
collection: "selected_collection"
}Related MCP Servers
| Server | Complements MongoDB By… |
|---|---|
| PostgreSQL MCP | Relational data |
| Filesystem MCP | Exporting data |
| Slack MCP | Sharing insights |
| Memory MCP | Remembering 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.