MongoDB That Works - MCP Server
It provides a MongoDB MCP server to query and manipulate MongoDB databases through any MCP client.
Discover collections and schemas (
listCollections,getSchema)Query documents (
find,findOne,count,distinct)Run aggregation pipelines (
aggregate)Modify data (
insertOne,updateOne,deleteOne)Support filtering, sorting, pagination, projections, and upserts
Automatically handle ObjectId conversion
Integrate with Claude, Codex, Cursor, VS Code, Zed, and other MCP clients via stdio
Provides tools for interacting with MongoDB, including schema discovery, document querying, aggregation, and CRUD operations on collections.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MongoDB That Works - MCP Server get schema for users collection"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MongoDB MCP That Works
A reliable MongoDB MCP (Model Context Protocol) server with built-in schema discovery and field validation. It's a standard MCP server over stdio, so it connects to any MCP client โ Claude Desktop, Claude Code, OpenAI Codex, Cursor, VS Code / GitHub Copilot, Zed, and more.
Published on npm:
@sourabhshegane/mongodb-mcp-that-worksยท Install withnpx -y @sourabhshegane/mongodb-mcp-that-works
This server connects to your MongoDB withfull read/write access to whatever user and database you supply via MONGODB_URI, and it exposes write tools (insertOne, updateOne, deleteOne) to any connected client. Only register it with MCP clients you trust. For high-risk environments, use a read-only MongoDB user or a dedicated database.
Features
๐ Schema Discovery: Automatically analyze collection structures
โ Field Validation: Prevent field name mistakes
๐ Full MongoDB Support: Find, aggregate, insert, update, delete operations
๐ High Performance: Efficient connection pooling and query optimization
๐ Secure: Support for MongoDB Atlas and authentication
๐ฏ Type-Safe: Built with TypeScript and Zod validation
Related MCP server: Mongo-MCP
Installation
Install from npm
npm install -g @sourabhshegane/mongodb-mcp-that-worksConfiguration
This is a standard stdio MCP server. Any MCP client launches it with npx and passes two environment variables:
Variable | Required | Description |
| Yes | MongoDB connection string, e.g. |
| No | Default database name (falls back to the URI's database) |
Every client below uses the same launch command:
npx -y @sourabhshegane/mongodb-mcp-that-works@latestThe -y flag auto-confirms the install so the client never hangs on an interactive prompt.
Security: never commit a real connection string. The examples use placeholders, or reference environment variables (
${env:...},env_vars,${input:...}) so credentials stay out of version control.
Claude Desktop
Edit your Claude Desktop config:
macOS:
~/Library/Application Support/Claude/claude_desktop_config.jsonWindows:
%APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "mongodb+srv://<user>:<password>@cluster.mongodb.net/<database>",
"MONGODB_DATABASE": "your_database_name"
}
}
}
}Claude Code
Add it with the CLI (anything after -- is the server command):
claude mcp add mongodb --scope user \
--env MONGODB_URI=mongodb+srv://<user>:<password>@cluster.mongodb.net/<database> \
-- npx -y @sourabhshegane/mongodb-mcp-that-works@latestOr commit a project-scoped .mcp.json (secrets referenced with ${VAR}):
{
"mcpServers": {
"mongodb": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "${MONGODB_URI}",
"MONGODB_DATABASE": "${MONGODB_DATABASE:-your_database_name}"
}
}
}
}Scopes: local โ ~/.claude.json, project โ .mcp.json, user โ ~/.claude.json. Verify with claude mcp list.
OpenAI Codex
Codex uses TOML (not JSON). Add to ~/.codex/config.toml (or project-scoped .codex/config.toml):
[mcp_servers.mongodb]
command = "npx"
args = ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"]
env = { MONGODB_URI = "mongodb+srv://<user>:<password>@cluster.mongodb.net/<database>", MONGODB_DATABASE = "your_database_name" }
startup_timeout_sec = 30Or forward variables from your shell instead of inlining them:
[mcp_servers.mongodb]
command = "npx"
args = ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"]
env_vars = ["MONGODB_URI", "MONGODB_DATABASE"]Or add it with the CLI: codex mcp add mongodb -- npx -y @sourabhshegane/mongodb-mcp-that-works@latest. Verify with codex mcp list.
Cursor
Project scope โ .cursor/mcp.json (commit it to share with your team). Global scope โ ~/.cursor/mcp.json.
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "${env:MONGODB_URI}",
"MONGODB_DATABASE": "${env:MONGODB_DATABASE}"
}
}
}
}VS Code / GitHub Copilot
For quick installation, click the buttons below. After install, replace the placeholder connection string in your config:
Note: VS Code's root key is servers (other clients use mcpServers), and type is required. .vscode/mcp.json:
{
"servers": {
"mongodb": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "${input:mongodb-uri}"
}
}
},
"inputs": [
{
"id": "mongodb-uri",
"type": "promptString",
"description": "MongoDB connection string",
"password": true
}
]
}Zed
Add to settings.json (~/.config/zed/settings.json or .zed/settings.json):
{
"mcp": {
"mongodb": {
"command": "npx",
"args": ["-y", "@sourabhshegane/mongodb-mcp-that-works@latest"],
"env": {
"MONGODB_URI": "mongodb+srv://<user>:<password>@cluster.mongodb.net/<database>"
}
}
}
}Available Tools
1. listCollections
List all collections in the database.
// Example
mcp.listCollections({ filter: {} })2. find
Find documents in a collection with filtering, sorting, and pagination.
// Example
mcp.find({
collection: "users",
filter: { status: "active" },
sort: { createdAt: -1 },
limit: 10
})3. findOne
Find a single document.
// Example
mcp.findOne({
collection: "users",
filter: { email: "user@example.com" }
})4. aggregate
Run aggregation pipelines.
// Example
mcp.aggregate({
collection: "orders",
pipeline: [
{ $match: { status: "completed" } },
{ $group: { _id: "$userId", total: { $sum: "$amount" } } }
]
})5. count
Count documents matching a filter.
// Example
mcp.count({
collection: "products",
filter: { inStock: true }
})6. distinct
Get distinct values for a field.
// Example
mcp.distinct({
collection: "orders",
field: "status"
})7. insertOne
Insert a single document.
// Example
mcp.insertOne({
collection: "users",
document: { name: "John Doe", email: "john@example.com" }
})8. updateOne
Update a single document.
// Example
mcp.updateOne({
collection: "users",
filter: { _id: "123" },
update: { $set: { status: "active" } }
})9. deleteOne
Delete a single document.
// Example
mcp.deleteOne({
collection: "users",
filter: { _id: "123" }
})10. getSchema
Analyze collection structure and discover field names.
// Example
mcp.getSchema({
collection: "users",
sampleSize: 100
})
// Returns:
{
"collection": "users",
"sampleSize": 100,
"fields": {
"_id": {
"types": ["ObjectId"],
"examples": ["507f1f77bcf86cd799439011"],
"frequency": "100/100",
"percentage": 100
},
"email": {
"types": ["string"],
"examples": ["user@example.com"],
"frequency": "100/100",
"percentage": 100
}
}
}Tool annotations (MCP hints)
Tools are annotated with MCP ToolAnnotations so clients can distinguish read-only tools from write-capable tools and flag operations that are destructive:
Tool | readOnlyHint | idempotentHint | destructiveHint | Notes |
|
| โ | โ | Pure read |
|
| โ | โ | Pure read |
|
| โ | โ | Pure read |
|
| โ | โ | Pure read (may also run write stages) |
|
| โ | โ | Pure read |
|
| โ | โ | Pure read |
|
| โ | โ | Pure read |
|
|
|
| Additive; retrying inserts a new document |
|
|
|
| Modifies existing docs; |
|
|
|
| Deleting an already-absent document is a no-op |
Note:
aggregateis annotated read-only, but it can contain write stages (e.g.$out,$merge) โ inspect pipelines before running.
Best Practices
Use Schema Discovery First: Before querying, run
getSchemato understand field namesHandle ObjectIds: The server automatically converts string IDs to ObjectIds
Use Projections: Limit returned fields to improve performance
Batch Operations: Use aggregation pipelines for complex queries
Examples
Basic Usage
// Get schema first to avoid field name mistakes
const schema = await mcp.getSchema({ collection: "reports" });
// Use correct field names from schema
const reports = await mcp.find({
collection: "reports",
filter: { organization_id: "64ba7374f8b63db2083b2665" },
limit: 10
});Advanced Aggregation
const analytics = await mcp.aggregate({
collection: "orders",
pipeline: [
{ $match: { createdAt: { $gte: new Date("2024-01-01") } } },
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } },
revenue: { $sum: "$amount" },
count: { $sum: 1 }
}},
{ $sort: { _id: 1 } }
]
});Debugging
You can use the MCP Inspector to debug the server, inspect tool schemas, and call tools interactively:
npx @modelcontextprotocol/inspector npx -y @sourabhshegane/mongodb-mcp-that-works@latestSet MONGODB_URI (and optionally MONGODB_DATABASE) in your environment before launching the inspector.
Troubleshooting
Connection Issues
Verify your MongoDB URI is correct
Check network connectivity to MongoDB Atlas
Ensure IP whitelist includes your current IP
Field Name Errors
Always use
getSchemato discover correct field namesRemember MongoDB is case-sensitive
Check for typos in nested field paths (e.g., "user.profile.name")
Performance
Use indexes for frequently queried fields
Limit result sets with
limitparameterUse projections to return only needed fields
Testing
The repo ships an automated test suite (node:test, no extra framework):
npm testThis first builds, then runs:
Unit tests (
tests/unit.test.mjs) โ MCP protocol: negotiated version, the 10 tool schemas, ToolAnnotations, and error handling. No database required.End-to-end tests (
tests/e2e.test.mjs) โ full CRUD tour against a real MongoDB (insertOneโfind/findOne/count/distinct/aggregateโupdateOneโgetSchemaโdeleteOne), plus ObjectId auto-conversion and idempotency checks. Auto-skips with a note when no MongoDB is reachable.
The suite connects to MongoDB at MONGODB_URI (default mongodb://127.0.0.1:27017) and uses a throwaway database it deletes afterward, so it's safe against any existing data. CI runs both suites against a real MongoDB (Docker mongo:7) on every push/PR.
Contributing
Contributions are welcome โ new tools, bug fixes, examples, and documentation improvements. Pull requests and issues are appreciated. See CHANGELOG.md for release history. For examples of other MCP servers, see the reference implementations.
License
MIT License - see LICENSE file for details
Changelog
See CHANGELOG.md for the full history.
Version | npm | GitHub Release | Highlights |
0.1.8 | Automated unit + e2e MongoDB test suite | ||
0.1.7 | ToolAnnotations, SDK 1.30, repo-standard docs | ||
0.1.6 | CI/CD, changelog, and repo badges | ||
0.1.5 | Post-migration metadata & ownership fixes | ||
0.1.3 | Published with | ||
0.1.2 | Repo URLs updated to mongodb-mcp-that-works | ||
0.1.0 | Initial release |
Releases
All versions published to npm also have tagged GitHub Releases with build checks. The repo uses GitHub Actions for continuous integration and automated publishing:
Tag pushes (
v*) trigger lint/build checks and, once checks pass, an automated npm publishEvery published version has a matching GitHub Release
Made out of pain since the official MongoDB MCP didn't work for me
Available Tools
10 toolsaggregateBRead-onlyIdempotent
Run an aggregation pipeline on a MongoDB collection
Inputs: pipeline (required), collection (required), limit.
countARead-onlyIdempotent
Count documents in a MongoDB collection
Inputs: collection (required), filter.
deleteOneADestructiveIdempotent
Delete a single document from a MongoDB collection
Inputs: filter (required), collection (required).
distinctBRead-onlyIdempotent
Get distinct values for a field in a MongoDB collection
Inputs: field (required), collection (required), filter.
findARead-onlyIdempotent
Find documents in a MongoDB collection
Inputs: collection (required), skip, sort, limit, +2 more.
findOneBRead-onlyIdempotent
Find a single document in a MongoDB collection
Inputs: collection (required), filter, projection.
getSchemaARead-onlyIdempotent
Analyze collection structure and return field names with types
Inputs: collection (required), sampleSize.
insertOneB
Insert a single document into a MongoDB collection
Inputs: document (required), collection (required).
listCollectionsARead-onlyIdempotent
List all collections in the database
Inputs: filter.
updateOneCDestructive
Update a single document in a MongoDB collection
Inputs: filter (required), update (required), collection (required), upsert.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 10 tools
Each tool targets a distinct MongoDB operation: find vs findOne are clearly differentiated (multiple vs single document), and aggregate, count, distinct, listCollections, insertOne, updateOne, deleteOne, and getSchema have no overlapping responsibilities. The descriptions clarify the purpose of each, leaving no ambiguity for an agent.
All tool names follow a consistent lowerCamelCase convention with a verb-first pattern (find, findOne, aggregate, count, distinct, listCollections, insertOne, updateOne, deleteOne, getSchema). The style is uniform and predictable, making it easy to infer tool behavior from the name.
With 10 tools, the server is well-scoped for a MongoDB interface. It covers querying, aggregation, schema inspection, and basic CRUD operations without unnecessary bloat. Each tool serves a clear purpose, and the count is ideal for an MCP server of this domain.
The tool surface covers the core CRUD operations (insertOne, updateOne, deleteOne, find, findOne) and includes useful extras like aggregate, count, distinct, and getSchema. However, it lacks bulk operations (insertMany, updateMany, deleteMany) and collection management (createCollection, dropCollection), which are common in MongoDB workflows. These are minor gaps that an agent can work around by composing single-document calls, but they are noticeable.
Maintenance
Related MCP Connectors
Hosted MCP server for AI-driven data ops. Create apps, manage schemas, and CRUD structured data.
Astra DB tools for agents: schema, find, vector search, guarded writes, and interactive views.
PostgreSQL, MySQL, OpenAPI/Swagger, and shared Agent Memory with scoped access.
Design domain models and generate deterministic multi-stack code, driven by your coding agent.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceEnables interaction with MongoDB databases through complete CRUD operations including connecting, creating, reading, updating, and deleting documents with support for filtering, pagination, and automatic ObjectId serialization.-
- AlicenseNot gradedqualityDmaintenanceEnables LLMs to interact with MongoDB databases through a complete suite of CRUD operations, administrative tasks, and index management tools. It supports database and collection handling, aggregation pipelines, and comprehensive server monitoring via the Model Context Protocol.142 PyPI3MIT
- AlicenseNot gradedqualityDmaintenanceEnables interaction with MongoDB databases through the Model Context Protocol, supporting CRUD operations, secure connections, and easy IDE integration.2 npm3MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact natively with MongoDB databases, including schema discovery, CRUD operations, aggregation pipelines, and index management via natural language.21 npmMIT