# MongoDB MCP Server: Build an AI Agent for Natural-Language Mongo Queries

> Spin up a hosted MongoDB MCP server in seconds — or self-host the official mongodb-mcp-server. Connect Claude, GPT-5, Gemini or DeepSeek and run queries, aggregation pipelines and schema audits in plain English.

**Source:** https://mcpplaygroundonline.com/blog/mongodb-mcp-server-natural-language-queries-ai-agent  
**Author:** Nikhil Tiwari  
**Published:** 2026-05-10  
**Updated:** 2026-05-18  
**Category:** Recipe  
**Reading time:** 14 min read

---

_Updated: May 18, 2026 — added the hosted MongoDB MCP option (one-click cloud deploy, live URL + bearer token)._

🍃 MCP Recipe

-   **What you'll build:** An AI agent that talks to MongoDB in natural language — queries, aggregations, schema inspection, and Atlas cluster management
-   **MCP server:** `mongodb-mcp-server` (official, maintained by mongodb-js)
-   **Fast path:** [Deploy hosted MongoDB MCP](/mcp-hosted) — live HTTPS URL + token in ~30 seconds, no install
-   **Local path:** 10–15 minutes (Node.js + connection string)
-   **Difficulty:** Beginner-friendly

⚡ Skip the install — spin up a hosted MongoDB MCP server in seconds

If you don't want to keep `npx mongodb-mcp-server` running on a laptop or pay for a long-lived VM, deploy the **hosted MongoDB MCP server** on MCP Playground. Same official `mongodb-mcp-server`, managed for you.

-   **Live HTTPS URL + bearer token in ~30 seconds** — paste your Mongo connection string into a form, click Deploy
-   Runs in an isolated cloud sandbox — your connection string never leaves the deployment, the URL is gated by the bearer token
-   Works with Claude Desktop, Cursor, Claude Code, MCP Agent Studio and any MCP-compatible agent
-   Free tier: 1 active server, 10 min/month. Pro tiers add more slots and runtime
-   Same tool surface (`find`, `aggregate`, `countDocuments`, `$indexStats`, Atlas Admin) — your prompts port 1:1

[Deploy hosted MongoDB MCP →](/mcp-hosted)

The **MongoDB MCP server** turns any Claude, GPT-5, Gemini, DeepSeek or Grok client into a Mongo-fluent analyst. It exposes your collections, the aggregation framework, indexes, the slow-query profiler and Atlas cluster controls as MCP tools — so you can ask _"show me daily signups for the last 30 days, broken down by source"_ and get an actual `aggregate()` pipeline run against your data.

This recipe covers both paths: the **hosted route** (~30 seconds, no install) for anyone who wants to get started immediately, and the **self-hosted route** for teams that need to run the server on their own network or against a database that's only reachable from a private VPC. The walkthrough then covers five queries that show off analytics, debugging and ops tasks, and explains connection-string mode (any Mongo) vs Atlas service-account mode (cluster management).

## What the MongoDB MCP Server Provides

The server is maintained by the official [mongodb-js org](https://github.com/mongodb-js/mongodb-mcp-server) and ships as the `mongodb-mcp-server` npm package. It exposes two distinct toolsets, depending on which credentials you pass at startup:

Toolset

How to enable

What you can do

**Database tools**

Pass `--connectionString "mongodb+srv://…"`

List databases and collections, run `find`, `aggregate`, `countDocuments`, inspect indexes, profile slow queries, infer schemas from samples

**Atlas tools**

Pass `--apiClientId` + `--apiClientSecret`

List clusters, check replica-set status, view metrics, manage database users, inspect Atlas Search indexes

You can pass both at once for a fully-armed agent. The `--readOnly` flag locks the server to non-mutating commands — strongly recommended until you trust write operations.

## Prerequisites

**Node.js 18+**

For `npx` — no global install needed

**A MongoDB cluster**

Local, Atlas, or self-hosted — anything reachable via a connection string

**Read-only DB user**

Strongly recommended — create a user with read-only roles for the DBs you want to expose

## Step 1: Start the Server with HTTP Transport

The default transport is stdio (good for Claude Desktop / Cursor). For browser-based clients like [MCP Agent Studio](/mcp-agent-studio) you need HTTP — pass `--transport http`:

```
npx -y mongodb-mcp-server@latest \
  --transport http \
  --connectionString "mongodb+srv://USER:PASS@your-cluster.mongodb.net/your-db" \
  --readOnly
```

The server listens on `http://127.0.0.1:3000` by default. Override with `--httpHost` and `--httpPort` if needed. Keep the process running — in production you'll want it under `pm2`, `systemd`, or in a container.

Security

The HTTP transport has **no built-in auth**. Run it on localhost only, or front it with a reverse proxy that adds an auth header before exposing it publicly. Never put a connection string with write privileges on a public endpoint.

## Step 2: Connect from MCP Agent Studio (Browser, No Install)

Easiest way to drive the server: [MCP Agent Studio](/mcp-agent-studio). Pick the pre-built [MongoDB Agent template](/templates/mongodb-agent) — it ships with a system prompt tuned for analytics, schema work and aggregation pipelines.

1.  Open [/templates/mongodb-agent](/templates/mongodb-agent) and click **Open in Studio**.
2.  Paste `http://localhost:3000/mcp` into the **MCP server URL** field.
3.  Pick a model — Claude Sonnet 4.5 is the default; Opus 4.7 is the strongest for complex aggregation pipelines.
4.  Send a first message: _"List all databases on this cluster."_

If you'd rather use Claude Desktop or Cursor, skip the `--transport http` flag — those clients speak stdio natively.

## Step 3: Five Queries That Show What the Agent Can Do

### 1\. Schema discovery

Prompt

"Sample 100 documents from the `users` collection and tell me the field types — flag any field that's sometimes missing or has inconsistent types."

The agent uses the `mongodb-aggregate` tool with a `$sample` stage, then infers the schema. Useful when joining a project with no schema docs, or when you suspect a producer is writing the wrong shape.

### 2\. Natural-language analytics

Prompt

"Daily signups for the last 30 days, grouped by signup source. Sort newest first."

The model writes a pipeline with `$match` on `createdAt`, `$group` by date and source, `$sort` descending. You see the pipeline before it runs — copy it into your code if you want to reuse it.

### 3\. Index audit

Prompt

"Which indexes on the `events` collection have not been used in the last 24 hours? Show me which ones I can safely drop."

Calls `$indexStats` and filters by `accesses.ops` and `accesses.since`. Surfaces dead indexes that are wasting RAM. Pair with the _"recommend an index for this slow query"_ prompt for a full index review.

### 4\. Slow-query triage

Prompt

"Look at `system.profile` from the last hour. Group slow queries by `ns` and tell me which collections are getting hammered, with the worst offending shape for each."

Requires the profiler to be enabled (`db.setProfilingLevel(1, { slowms: 100 })`). The agent groups queries by namespace, surfaces the worst `command` shape, and suggests an index when the answer is obvious.

### 5\. Atlas cluster snapshot

Prompt

"Give me a one-paragraph status of every cluster in this Atlas project — name, region, tier, and any node that's lagging in replica set sync."

Only works when you start the server with `--apiClientId` + `--apiClientSecret`. The Atlas toolset uses the public Atlas Admin API under the hood.

## Picking the Right Model

Mongo aggregation pipelines are non-trivial to write, so model choice matters more here than for, say, a Slack-message agent.

Model

When to pick it

**Claude Opus 4.7**

Complex multi-stage pipelines, schema inference across heterogeneous documents, when correctness > cost

**Claude Sonnet 4.5**

Default. Handles 95% of analytics queries, much cheaper

**GPT-5.4**

Strong on Atlas-side ops (cluster status, user management); slightly weaker than Claude on aggregation pipeline composition

**DeepSeek V4 Pro**

Cheapest competent option — good for batch jobs that run the same prompt against many collections

Use [Compare mode](/mcp-agent-studio) in Agent Studio to send the same Mongo prompt to two models side-by-side — you'll see whose pipeline is correct in seconds.

## Connection String vs Atlas Service Account

Two auth modes, two different sets of tools — easy to confuse:

-   **Connection string** (`--connectionString`): Standard MongoDB URI. The agent can read/write data and inspect schemas. Works with any Mongo (local, Atlas, RDS-style hosted Mongo, self-hosted). **This is what you want for analytics.**
-   **Atlas service account** (`--apiClientId` + `--apiClientSecret`): Atlas Admin API credentials. The agent can manage clusters, users, network access lists, and Search indexes — but cannot read your data. **This is what you want for ops.**

Pass both for the full picture. Create the service account at [cloud.mongodb.com](https://cloud.mongodb.com/) → **Access Manager → Service Accounts**.

## Production Notes

-   **Always pair `--readOnly` with prod connection strings** until you've verified the system prompt prevents accidental writes.
-   **Use a dedicated read-only DB user.** Don't reuse the user your app writes with. Grant only the databases the agent should see.
-   **The HTTP transport has no auth.** Bind to `127.0.0.1`, or front with an auth proxy. Never expose `0.0.0.0:3000` to the public internet.
-   **Profiler queries can be heavy.** If you enable the slow-query profiler, scope it to a database (not all of them) and use `slowms: 100` or higher.
-   **Aggregation result sizes** can blow up the model's context window. The default system prompt in the [MongoDB Agent template](/templates/mongodb-agent) caps results at 50 documents — keep that in your own prompts.

Skip the install — get a hosted MongoDB MCP in 30 seconds

Live HTTPS URL + bearer token, managed cloud sandbox. Works with Claude Desktop, Cursor, MCP Agent Studio and any MCP-compatible agent. Free tier available.

[Deploy hosted MongoDB MCP →](/mcp-hosted) [Open MongoDB Agent template](/templates/mongodb-agent)

## Related Recipes

-   [PostgreSQL MCP: Build a Claude Analytics Agent](/blog/postgres-mcp-claude-analytics-agent-recipe)
-   [Build an AI Database Query Assistant (Supabase MCP)](/blog/build-ai-database-query-assistant-natural-language-sql)
-   [Best AI Model for MCP Tool Calling](/blog/best-ai-model-for-mcp-tool-calling)

## Frequently Asked Questions

**Hosted vs self-hosted MongoDB MCP — which should I use?**

Use **hosted** (on [/mcp-hosted](/mcp-hosted)) when you want to be running queries in ~30 seconds, your Mongo cluster is reachable from the public internet (Atlas, RDS-style hosted Mongo, anything not VPC-private), and you don't want to keep a process running on a laptop. Use **self-hosted** when your database is VPC-private or on a corporate network, you have hard data-residency requirements, or you're integrating into a CI runner that already has Node available. Both expose the same official `mongodb-mcp-server` tool surface — your prompts and pipelines port 1:1.

**Does the official MongoDB MCP server support write operations?**

Yes — by default it can run `insert`, `update`, `delete` and DDL commands. Pass `--readOnly` to lock it to non-mutating commands. Until you trust the system prompt, always pair production credentials with `--readOnly`.

**Is there a hosted MongoDB MCP server I can use without running anything myself?**

Yes — [MCP Playground](/mcp-hosted) offers a managed deployment of the official `mongodb-mcp-server`. Click **MongoDB** on [/mcp-hosted](/mcp-hosted), paste your connection string, click Deploy — you get a live HTTPS URL and bearer token in ~30 seconds. There's still no first-party endpoint at a URL like `mcp.mongodb.com` from MongoDB Inc., so for now the hosted option is either MCP Playground's managed deployment or self-hosting on your own infrastructure.

**Can I use this with MongoDB Atlas?**

Yes — pass your Atlas connection string to `--connectionString` for data tools, and an Atlas service-account client ID + secret to `--apiClientId` / `--apiClientSecret` for cluster-management tools. You can pass both at the same time.

**Why does the agent need to see my schema first?**

MongoDB is schema-less, so the model can't generate correct queries without seeing real document shapes. The first thing the agent typically does is sample a collection (`$sample` stage) to learn field names and types. This is normal — once it has the schema for a collection it caches it for the rest of the conversation.

**Which AI model is best for MongoDB aggregation pipelines?**

For complex multi-stage pipelines, Claude Opus 4.7 and Claude Sonnet 4.5 are the strongest. GPT-5.4 is competitive but occasionally botches stage ordering. DeepSeek V4 Pro is the cheapest option that still gets non-trivial pipelines right. Use [Compare mode](/mcp-agent-studio) in Agent Studio to test on your own collection.

## Frequently asked questions

### Does the official MongoDB MCP server support write operations?

Yes — by default it can run insert, update, delete and DDL commands. Pass --readOnly to lock it to non-mutating commands. Until you trust the system prompt, always pair production credentials with --readOnly.

### Is there a hosted MongoDB MCP endpoint, like Supabase has?

No. As of May 2026, there is no hosted MCP endpoint at a URL like mcp.mongodb.com. You self-host the official mongodb-mcp-server with your connection string, then point any MCP client at it.

### Can I use this with MongoDB Atlas?

Yes — pass your Atlas connection string to --connectionString for data tools, and an Atlas service-account client ID + secret to --apiClientId / --apiClientSecret for cluster-management tools. You can pass both at the same time.

### Why does the agent need to see my schema first?

MongoDB is schema-less, so the model cannot generate correct queries without seeing real document shapes. The first thing the agent typically does is sample a collection ($sample stage) to learn field names and types. This is normal — once it has the schema for a collection it caches it for the rest of the conversation.

### Which AI model is best for MongoDB aggregation pipelines?

For complex multi-stage pipelines, Claude Opus 4.7 and Claude Sonnet 4.5 are the strongest. GPT-5.4 is competitive but occasionally botches stage ordering. DeepSeek V4 Pro is the cheapest option that still gets non-trivial pipelines right.


---

_Canonical page: https://mcpplaygroundonline.com/blog/mongodb-mcp-server-natural-language-queries-ai-agent — MCP Playground (mcpplaygroundonline.com), the free browser-based tool for testing MCP servers and building AI agents._
