Agentbrisk
database TypeScript Official

MongoDB MCP Server

Query and inspect MongoDB databases from AI agents with the official MongoDB MCP server


The MongoDB MCP server is the official MongoDB implementation of the Model Context Protocol, maintained by MongoDB, Inc. through the mongodb-js organization. It exposes tools for listing databases and collections, inspecting schemas, running aggregation pipelines, and querying documents. It connects to any MongoDB deployment, including Atlas, local instances, and self-hosted replica sets, via a standard connection string.

When you're debugging a backend service that uses MongoDB, having to switch context to a MongoDB client, write the query, interpret the result, then switch back to the conversation is friction that adds up. The MongoDB MCP server removes that step: the agent can query your collections directly, inspect schemas, and run aggregations without you leaving the conversation.

This is an official server from MongoDB, Inc., which matters both for reliability and for the fact that it's updated alongside MongoDB driver releases rather than depending on a community maintainer to keep up.

What the server exposes

The MongoDB MCP server maps MongoDB's core operations onto a set of agent-callable tools. The surface area covers the read side of MongoDB thoroughly.

List databases returns all databases in the deployment with their storage stats. This is usually the first call an agent makes when you ask it to explore an unfamiliar MongoDB instance.

List collections returns the collections in a specific database. The agent gets collection names and basic metadata. Paired with the schema inspection tool, this is how the agent builds a working understanding of your data model.

Find runs a MongoDB query against a collection. You pass a filter document in standard MongoDB query syntax and get matching documents back. The server handles projection, sort, limit, and skip, so the agent can page through large result sets or fetch specific fields without returning entire documents.

Count returns the number of documents matching a filter. Faster and cheaper than fetching documents when you just need a number.

Aggregate runs an aggregation pipeline. This is the most powerful tool in the set. A properly constructed aggregation can do joins via $lookup, compute statistics with $group, filter through multiple stages, or run $vectorSearch on an Atlas cluster with vector indexes configured. The agent constructs the pipeline stages and the server executes them.

Distinct returns the unique values of a field across a collection. Useful for exploring what values a categorical field actually takes, or finding all unique identifiers in a dataset.

Get schema introspects a collection by sampling documents and inferring the schema. MongoDB is schema-flexible, so this is an approximation based on the sample, but it gives the agent a much better picture than guessing from collection names alone.

List indexes returns the index definitions for a collection. Relevant when the agent is helping you understand query performance or figure out why a query is slow.

Setup

The simplest install path is npx, which runs the server without a global install. Test your connection string first:

npx -y mongodb-mcp-server --uri "mongodb://localhost:27017"

If the server connects and the tool list prints, your URI is correct. For Atlas:

npx -y mongodb-mcp-server --uri "mongodb+srv://user:[email protected]/mydb"

Once confirmed, add the server to your MCP client config. For Claude Desktop at ~/Library/Application Support/Claude/claude_desktop_config.json:

{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": ["-y", "mongodb-mcp-server"],
      "env": {
        "MONGODB_URI": "mongodb://user:password@localhost:27017/mydb"
      }
    }
  }
}

Passing the URI through an environment variable keeps it out of the args array, which ends up in process listings on shared machines. On macOS, you can set environment variables in the shell profile or in the env block of the config as shown above.

For Claude Code, the config file is at ~/.claude/mcp.json with the same structure.

Connecting to Atlas with a config file:

The server also accepts a YAML or JSON configuration file if you prefer not to use environment variables:

{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "-y",
        "mongodb-mcp-server",
        "--config",
        "/Users/you/.mongodb-mcp.json"
      ]
    }
  }
}

Where ~/.mongodb-mcp.json holds your connection string and any other options outside your MCP client config.

Common use cases

Schema exploration on an unfamiliar codebase. When you join a project using MongoDB, the agent can systematically walk through databases and collections, inspect sampled schemas, and produce a written overview of the data model. This is faster than reading code and more accurate than asking someone who may not remember what fields are actually in production.

Query debugging. You describe the data you expect and the agent writes and runs the query. If it comes back wrong, the agent can examine the result, adjust the filter or aggregation, and try again. The loop is tighter than switching between a query editor and your conversation.

Aggregation development. Aggregation pipelines in MongoDB can get complex fast. An agent with access to your collection can prototype a pipeline, run it, and refine it based on actual output rather than hypothetical documents. For one-off analytics or ETL transformations, this is significantly faster than writing, deploying, and debugging the pipeline manually.

Data quality checks. An agent can count documents, find nulls in required fields, identify documents where a field takes unexpected values, or verify that index definitions match what your application expects. These are the kinds of checks that get skipped in manual review and caught after deployment.

Performance investigation. Combined with schema inspection and index listing, the agent can look at a slow query, examine the relevant indexes, and suggest either a query rewrite or an index addition. It is not a substitute for explain() and a real performance engineer, but for obvious index gaps it gets there fast.

Atlas Vector Search queries. If you're using Atlas Vector Search, the agent can construct and run $vectorSearch aggregation stages. You'd describe the query intent and the agent writes the pipeline including the vector field name, numCandidates, and limit parameters appropriate for your index.

Document design and schema flexibility

One thing that makes MongoDB MCP different from Postgres MCP or SQLite MCP is schema flexibility. MongoDB does not enforce a schema at the database level, which means the agent's schema inference is a sample-based approximation, not a ground truth.

The practical consequence: if your collection has inconsistent document structure (a common pattern in MongoDB that starts as intentional and becomes messy over time), the schema tool may not surface all the field combinations. The agent can still query correctly, but it may miss optional fields that do not appear in the sampled documents.

For this reason, it is useful to tell the agent about your data model explicitly when you know it, rather than relying entirely on schema inference. "Documents in the users collection always have an email field and optionally a phone field" is more accurate than letting the agent sample 100 documents and guess.

Security considerations

MongoDB's access control model is role-based. The principle here is the same as with any database MCP server: create a dedicated user with only the permissions the agent actually needs.

For a read-only agent:

db.createUser({
  user: "mcp_agent",
  pwd: "strongpassword",
  roles: [
    { role: "read", db: "mydb" },
    { role: "read", db: "otherdb" }
  ]
})

The read built-in role in MongoDB grants find, aggregate, and listCollections on the specified database. It does not grant insert, update, delete, or any admin operations.

For Atlas, create the user in the Atlas security settings under "Database Access" and assign the built-in role "Read Only" for the specific clusters or databases you want the agent to access. Atlas also lets you restrict access by IP allowlist, which is worth enabling even for development clusters.

Connection string hygiene: The MongoDB URI often contains credentials directly. Keep it in an environment variable or a file outside your project directory. If you're using Atlas, consider using a connection string with a dedicated user rather than the admin credential you use for the Console.

No production write access. Even if a version of the server exposes write tools, do not connect a write-enabled MCP server to a production MongoDB deployment without a very specific reason and additional safeguards. The read tools cover the majority of useful agent workflows.

Comparing to the Postgres and SQLite servers

The three database MCP servers serve different database paradigms, but they share a common setup pattern. If you have used the Postgres MCP server or SQLite MCP, the MongoDB server will feel familiar.

The key difference is the query language. Instead of SQL, the agent works with MongoDB's document-oriented filter syntax and aggregation pipeline DSL. The agent needs to know MongoDB query operators ($eq, $in, $regex, $lookup) to be useful. Claude handles this reasonably well because MongoDB's query language is widely represented in its training data, but complex pipelines sometimes need a prompt that specifies the expected output format to avoid pipeline errors.

For teams that use MongoDB alongside a relational database, running both the MongoDB and Postgres MCP servers simultaneously is valid. You can have the agent query both in a single session when a question spans both data stores.

Bottom line

The MongoDB MCP server is well-suited for development workflows where you need to explore data, prototype queries, and iterate on aggregations without leaving your conversation. The official maintenance from MongoDB, Inc. means it tracks the driver and Atlas API rather than lagging behind them.

The setup is about as simple as database MCP servers get: a connection string, an npx command, and a config entry. The read tool set covers the vast majority of what you'd actually want an agent to do with a database, and the aggregation tool puts real analytical power in the agent's hands.

The security story is standard: use a dedicated read-only user, keep the connection string out of version control, and do not connect to production with write permissions enabled unless you have a specific reason and the access controls to match.

Features

  • List all databases and collections in a MongoDB deployment
  • Query documents using MongoDB filter syntax
  • Run aggregation pipelines for complex data analysis
  • Inspect collection schemas and index definitions
  • Count documents with optional filter conditions
  • Retrieve distinct field values across a collection
  • Works with MongoDB Atlas, local instances, and self-hosted clusters
  • Supports standard MongoDB connection strings including Atlas SRV format
  • Configurable read preference (primary, secondary, nearest)

How to set up the MongoDB MCP Server MCP server

  1. Prepare your MongoDB connection string (mongodb:// for local or mongodb+srv:// for Atlas)
  2. Run npx -y mongodb-mcp-server to test the connection
  3. Add the server block to your Claude Desktop or Claude Code MCP config file
  4. Set the MONGODB_URI environment variable or pass the URI as an argument
  5. Restart your MCP client and verify the MongoDB tools appear in the tool list

Frequently Asked Questions

What is the MongoDB MCP server?
The MongoDB MCP server is an official implementation from MongoDB, Inc. that gives AI agents tools to explore and query MongoDB databases through the Model Context Protocol. It exposes tools for listing collections, querying documents, running aggregations, and inspecting schemas. It works with any MongoDB deployment accessible via a standard connection string.
Does the MongoDB MCP server support write operations?
The server primarily targets read and analysis operations. It includes tools for querying, counting, and aggregating, which are safe for read-only workflows. Some versions include insert or update capabilities. For anything modifying production data, use a database user with restricted permissions regardless of what the server exposes at the tool level.
Does the MongoDB MCP server work with MongoDB Atlas?
Yes. Atlas uses the standard mongodb+srv:// connection string format, which the server supports natively. You can also run Atlas-specific aggregation pipelines like $search for vector similarity or full-text search. The server handles Atlas connection strings the same way any MongoDB driver does.
How do I connect the MongoDB MCP server to a local MongoDB instance?
Use a standard mongodb:// connection string. For a local instance with default settings, that is mongodb://localhost:27017. If your instance has auth enabled, include the username and password in the URI: mongodb://user:password@localhost:27017/mydb?authSource=admin.
Can I use the MongoDB MCP server for Atlas Vector Search?
The server can execute aggregation pipelines, which means you can pass a $vectorSearch stage to an Atlas cluster that has vector search configured. The AI agent would construct and run the pipeline via the aggregation tool. This is not a dedicated vector search tool, but it works for teams already using Atlas Vector Search who want to query it through MCP.
What are the security considerations for MongoDB MCP?
Use a dedicated MongoDB user with the minimum required privileges. For read-only workloads, grant the read built-in role on the specific databases the agent needs. Avoid connecting with an Atlas admin credential or a user with readWriteAnyDatabase. Store the connection string in an environment variable rather than embedding it in config files, especially on shared machines.
Search