← Back to dashboard
mongodbdatabasefreshReader view (for NotebookLM)

MongoDB Integration Guide

What is MongoDB?

The real model

mongodb 7.7 + one module-scoped MongoClient, registered with attachDatabasePool on Vercel.

Driver 7.x and Mongoose 9 need Node 20.19+. On Vercel, install Atlas from the Marketplace (it injects MONGODB_URI), create the client once at module scope with maxIdleTimeMS: 5000, and call attachDatabasePool(client) from @vercel/functions so Fluid compute closes idle sockets before suspending. The Data API is end-of-life, so Edge code has no HTTP escape hatch. For RAG, an autoEmbed vector index has Atlas embed text with Voyage AI (voyage-4, $0.06 per 1M tokens). For codeAmani it's a client-driven choice: Neon Postgres stays the default, and Kenya-targeted builds use Atlas AF_SOUTH_1 (Cape Town) next to Vercel cpt1.

Five MongoDB primitives

A document store you reach for only when Postgres jsonb won't do.

Text
███╗   ███╗ ██████╗ ███╗   ██╗ ██████╗  ██████╗ ██████╗ ██████╗
████╗ ████║██╔═══██╗████╗  ██║██╔════╝ ██╔═══██╗██╔══██╗██╔══██╗
██╔████╔██║██║   ██║██╔██╗ ██║██║  ███╗██║   ██║██║  ██║██████╔╝
██║╚██╔╝██║██║   ██║██║╚██╗██║██║   ██║██║   ██║██║  ██║██╔══██╗
██║ ╚═╝ ██║╚██████╔╝██║ ╚████║╚██████╔╝╚██████╔╝██████╔╝██████╔╝
╚═╝     ╚═╝ ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝  ╚═════╝ ╚═════╝ ╚═════╝

MongoDB Integration Guide

Focus: When and how codeAmani uses MongoDB for client projects that require a document database. Covers picking an Atlas tier (Free / Flex / Dedicated), provisioning through the Vercel Marketplace, connection reuse on Vercel Fluid compute with attachDatabasePool, Mongoose with Zod at the boundary, the aggregation pipeline, transactions, MongoDB Vector Search with Voyage AI embeddings, region choice for Kenya-targeted builds, and setting up (and un-sticking) the MongoDB MCP server in Claude Code.

Overview

MongoDB is a document database advertised as an option on motionstackstudios.com. It stores BSON documents in collections rather than rows in tables. That flexibility (nested objects, arrays, a different shape per document) is the whole point, and it's also why MongoDB is not the house default.

The house default for almost everything is Neon Postgres + Drizzle ORM, with Supabase as the second relational option. Postgres jsonb columns cover a lot of "document-ish" needs while keeping strong typing, joins, transactions and per-PR branching. MongoDB earns a place only when a client build specifically needs a document model: a schema that keeps changing, deeply nested data that would be painful to normalize, or per-tenant documents whose fields differ per customer.

Check first. Before adding MongoDB to a build, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm the Neon/Postgres default (including jsonb) won't meet the requirement. MongoDB adds a second database paradigm, its own ODM, and its own connection-pool pitfalls on serverless.

Official Documentation

Versions (verified on npm 2026-10-20)

PackageVersionNotes
mongodb (Node driver)7.7.0 (2026-09-28)Node >= 20.19.0. v6 line still published as 6.21.0.
mongoose9.11.2 (2026-10-12)Node >= 20.19.0. v8 maintained as 8.24.5.
@vercel/functions3.10.1Provides attachDatabasePool and waitUntil.
mongodb-mcp-server3.1.0 (2026-10-15)Node ^20.19.0 || ^22.13.0 || >=24.0.0.
mongodb-client-encryption7.2.1Only for Queryable Encryption / CSFLE.
MongoDB Server9.0 current stableAtlas Flex runs at least 8.0.

Driver 7.x highlights since 7.0 (2025-11): 7.1 built-in MONGODB-AWS auth (no aws4) and exponential backoff in withTransaction(); 7.2 experimental runtimeAdapters and Web-standard Uint8Array / globalThis.crypto instead of Buffer / crypto; 7.3 deprecated MongoDB Server 4.2 and fixed SCRAM auth in Deno; 7.4 made Symbol.asyncDispose (await using) stable; 7.5 made Queryable Encryption prefix/suffix/substring queries GA (Server 9.0); 7.6 dropped Server 4.2, added baseBackoffMS, faster insertMany / bulkWrite, and an ESM-bundling fix; 7.7 fixed an OIDC bug where one failed token fetch poisoned the whole client.


Atlas tiers after the Serverless / Shared retirement

Atlas Serverless instances and the old M2/M5 Shared tiers are gone. You couldn't create them after February 2025, and Atlas stopped supporting them on 2026-01-22. M2/M5 clusters were migrated to Flex; Serverless instances were migrated to Free, Flex or Dedicated depending on usage. Update any Terraform/CLI/API code that still names the old types. Provision only these:

TierPrice (Oct 2026)StorageLimits that matterUse for
Free (M0)$0512 MB100 ops/s, 500 connections, 10 GB in + 10 GB out per 7 days, no backups, auto-pauses after 30 idle daysLearning, demos
Flex$0.011/hr, capped at $30/monthup to 5 GB500 ops/s, 500 connections, max 50 aggregation stages, no allowDiskUse, one daily snapshot, no private endpoints, no Performance AdvisorDev, staging, low-traffic client apps
Dedicated (M10+)from $0.08/hr (about $56.94/month for M10)10 GB → 4 TB/nodeFull feature set; auto-scaling; 99.995% SLAProduction, regulated data
Atlas Infinite (public preview)from $0.09/hr (about $65/month)up to 128 TB per HA shardM10+ only; decoupled compute and storageSpiky AI-scale workloads (not yet for client prod)

Search and Vector Search run on the cluster by default. Dedicated Search Nodes (S20 at $0.12/hr and up, us-east-1 prices) are an M10+ add-on. Re-check https://www.mongodb.com/pricing before quoting a client.

Choosing a region (Kenya-targeted projects)

There's no Atlas region in East Africa. The nearest are in South Africa, and only one supports the cheap tiers:

Atlas regionProvider / locationFreeFlexM10+
AF_SOUTH_1AWS af-south-1, Cape Town✅✅✅
SOUTH_AFRICA_NORTHAzure southafricanorth, Johannesburg——✅
AFRICA_SOUTH_1Google Cloud africa-south1, Johannesburg——✅ (no Search Nodes)
SOUTH_AFRICA_WESTAzure southafricawest, Cape Town——✅
  • Default for Kenya-targeted builds: AF_SOUTH_1 (AWS Cape Town), paired with Vercel region cpt1, which is also AWS af-south-1. Function and database sit in the same AWS region, and you can start on Free or Flex.
  • Johannesburg is dedicated-only (M10+ on Azure or Google Cloud). Pick it only when a client contract names Johannesburg, and budget at least M10.
  • Atlas Infinite isn't offered in af-south-1.
  • US-first projects (the default) stay in the Vercel project's region, usually iad1 with Atlas US_EAST_1.

Provisioning

Option A — Vercel Marketplace native integration (preferred on Vercel)

Vercel Marketplace → Storage → MongoDB Atlas → Install. You pick a tier (Free, Flex or Dedicated), a Vercel region (mapped to the closest Atlas region), and an installation plan:

  • Free plan: no card, Free clusters only.
  • Paid plan: card required; Flex and Dedicated are billed through your Vercel invoice. Creating one Flex or Dedicated cluster switches the whole installation to Paid. Going back to Free means uninstalling and reinstalling.

What it does for you:

  • Creates a Vercel-managed Atlas organization + project and injects MONGODB_URI into the linked Vercel project's environments (vercel env pull to get it locally).
  • Adds 0.0.0.0/0 to the Atlas IP access list (Vercel egress IPs are dynamic) and creates a DB user named Vercel-Admin-<resource> with readWriteAnyDatabase. For client data, create a narrower user (readWrite on one database) and swap the URI.
  • Installs MongoDB's agent skills (mongodb-schema-design, mongodb-query-optimizer, mongodb-search-and-ai).
  • Signs you into Atlas through Vercel SSO. Vercel "Admin"/"User" map to Atlas Organization Owner/Read Only.

Starter: npx create-next-app --example with-mongodb my-mongodb-app, then vercel link and vercel env pull.

Option B — Atlas directly (non-Vercel hosts, or client-owned Atlas orgs)

  1. Create a project and a cluster (Free, Flex or M10+) in the region chosen above.
  2. Database Access: create a user scoped to the app's database.
  3. Network Access: allow the platform's egress. Serverless hosts have dynamic IPs, so you typically need 0.0.0.0/0 and rely on TLS + SCRAM + a strong password. Use private endpoints (M10+) when the host supports them.
  4. Connect → Drivers: copy the SRV string.
Bash
mongodb+srv://<user>:<urlEncodedPassword>@cluster0.xxxxx.mongodb.net/<dbName>?retryWrites=true&w=majority&appName=acme-app

Gotcha: URL-encode the password. A literal @, :, / or # breaks parsing, so P@ss:w0rd becomes P%40ss%3Aw0rd.


Connection reuse on Vercel Fluid compute

Fluid compute is the default for new Vercel projects. Concurrent requests share one function instance and its globals, so one module-scoped MongoClient per instance is the right model. The remaining problem is suspension: idle sockets don't time out while an instance is frozen, so they pile up as "phantom" connections against the Atlas limit (500 on Free/Flex). attachDatabasePool from @vercel/functions fixes that. It uses waitUntil to keep the instance alive just long enough to close idle connections before suspending. Vercel lists MongoDB among the supported pool types.

TypeScript
// lib/mongodb.ts  (full file: examples/lib-mongodb.ts)
import { MongoClient, type Db, type MongoClientOptions } from "mongodb";
import { attachDatabasePool } from "@vercel/functions";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Missing MONGODB_URI environment variable");
const mongoUri: string = uri;

const options: MongoClientOptions = {
  appName: "codeamani-app",
  maxIdleTimeMS: 5000, // Vercel recommends a short idle timeout
  maxPoolSize: 10,
};

function createClient(): MongoClient {
  const client = new MongoClient(mongoUri, options);
  attachDatabasePool(client); // close idle connections before suspension
  return client;
}

const globalForMongo = globalThis as typeof globalThis & { _mongoClient?: MongoClient };
export const client: MongoClient = globalForMongo._mongoClient ?? createClient();
globalForMongo._mongoClient = client;

export function getDb(name: string = process.env.MONGODB_DB ?? "app"): Db {
  return client.db(name);
}

Rules:

  • Create the client once, at module scope. Don't create a new MongoClient() per request, and never client.close() in a handler.
  • No explicit connect() needed. The driver connects lazily on the first operation, which is how Vercel's own snippet works.
  • Don't wrap the shared client in await using. Driver 7.4 made Symbol.asyncDispose stable, so await using would close the client when the scope exits. Use it only in scripts and tests.
  • Don't set maxPoolSize: 1. Vercel warns it hurts concurrency on Fluid without reducing total connections.
  • Use rolling releases on big deploys so a fleet of fresh instances doesn't open connections all at once.
  • Node.js runtime only. The driver doesn't run on the Edge runtime. Keep export const runtime = "nodejs" (the Next.js default) on routes that touch MongoDB.

Netlify / other serverless hosts: there's no attachDatabasePool. Keep the same module-scoped client and set maxIdleTimeMS. The rest of the pattern is identical.

Mongoose — cached connection

TypeScript
// lib/dbConnect.ts  (full file: examples/lib-dbConnect.ts)
import mongoose from "mongoose";
import { attachDatabasePool } from "@vercel/functions";

const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Missing MONGODB_URI environment variable");
const mongoUri: string = uri;

interface MongooseCache { conn: typeof mongoose | null; promise: Promise<typeof mongoose> | null }
const globalForMongoose = globalThis as typeof globalThis & { _mongoose?: MongooseCache };
const cached: MongooseCache = globalForMongoose._mongoose ?? { conn: null, promise: null };
globalForMongoose._mongoose = cached;

export async function dbConnect(): Promise<typeof mongoose> {
  if (cached.conn) return cached.conn;
  if (!cached.promise) {
    cached.promise = mongoose
      .connect(mongoUri, { bufferCommands: false, maxPoolSize: 10, maxIdleTimeMS: 5000 })
      .then((m) => {
        attachDatabasePool(m.connection.getClient()); // the underlying MongoClient
        return m;
      });
  }
  try {
    cached.conn = await cached.promise;
  } catch (err) {
    cached.promise = null; // don't cache a failed connect
    throw err;
  }
  return cached.conn;
}

Mongoose schema + Zod at the boundary

Validate untrusted input with Zod first, then persist with a typed Mongoose model. Zod guards request bodies and webhooks; the Mongoose schema is the persistence contract. Full file: examples/provider-model.ts.

TypeScript
import { Schema, model, models, type InferSchemaType, type Model } from "mongoose";
import { z } from "zod";
import { dbConnect } from "@/lib/dbConnect";

export const ProviderInput = z.object({
  name: z.string().min(1),
  licenseType: z.enum(["APD", "AHCA", "DCF"]),
  email: z.email(), // Zod 4; z.string().email() is deprecated
  services: z.array(z.string()).default([]),
  metadata: z.record(z.string(), z.unknown()).optional(),
});

const providerSchema = new Schema(
  {
    name: { type: String, required: true, trim: true },
    licenseType: { type: String, required: true, enum: ["APD", "AHCA", "DCF"] },
    email: { type: String, required: true, lowercase: true, index: true },
    services: { type: [String], default: [] },
    metadata: { type: Schema.Types.Mixed },
  },
  { timestamps: true, strict: true },
);
export type Provider = InferSchemaType<typeof providerSchema>;

// Reuse the compiled model across hot reloads / warm invocations (avoids OverwriteModelError).
export const ProviderModel: Model<Provider> =
  (models.Provider as Model<Provider> | undefined) ?? model<Provider>("Provider", providerSchema);

export const runtime = "nodejs";

export async function POST(req: Request): Promise<Response> {
  const parsed = ProviderInput.safeParse(await req.json());
  if (!parsed.success) return Response.json({ error: z.flattenError(parsed.error) }, { status: 400 });
  await dbConnect();
  const provider = await ProviderModel.create(parsed.data);
  return Response.json({ id: provider._id.toString() }, { status: 201 });
}

Mongoose 9 changes that bite: pre middleware no longer receives next() (return or throw instead), and UUIDs come back as bson.UUID. Also add a collection-level $jsonSchema validator as a backstop for writes that bypass Mongoose (scripts, the MCP server, other services).


Aggregation pipeline

Stages run in order, and each stage's output feeds the next. Full file: examples/queries.ts.

TypeScript
export async function providerIntakeSummary(licenseType: "APD" | "AHCA" | "DCF") {
  return getDb()
    .collection<ProviderDoc>("providers")
    .aggregate<{ name: string; email: string; openIntakes: number }>([
      { $match: { licenseType } },
      { $lookup: { from: "intakes", localField: "_id", foreignField: "providerId", as: "intakes" } },
      {
        $project: {
          _id: 0, name: 1, email: 1,
          openIntakes: { $size: { $filter: { input: "$intakes", as: "i", cond: { $eq: ["$$i.status", "open"] } } } },
        },
      },
      { $sort: { openIntakes: -1 } },
      { $limit: 50 },
    ])
    .toArray();
}

Index the early $match / $sort fields and confirm IXSCAN (not COLLSCAN) with explain or the MCP explain tool. Flex caps pipelines at 50 stages and doesn't support allowDiskUse.

Transactions

Every Atlas cluster is a replica set, so multi-document ACID transactions work everywhere. withTransaction() handles commit/abort and retries transient errors. Since driver 7.1, it also backs off exponentially between retries.

TypeScript
export async function recordIntake(providerId: string, notes?: string): Promise<void> {
  const db = getDb();
  const id = new ObjectId(providerId);
  const session = client.startSession();
  try {
    await session.withTransaction(async () => {
      await db.collection<IntakeDoc>("intakes").insertOne({ providerId: id, status: "open", notes }, { session });
      await db.collection<ProviderDoc>("providers").updateOne({ _id: id }, { $inc: { openCount: 1 } }, { session });
    });
  } finally {
    await session.endSession();
  }
}

Transactions hold locks and add latency (60-second default limit). Embedding related data in one document often removes the need for one.


MongoDB Vector Search with Voyage AI

MongoDB owns Voyage AI. Its embedding models are served by Atlas, and Vector Search can call them for you. There are two ways to use it (full file: examples/vector-search-voyage.ts):

A. Automated Embedding (autoEmbed), the least code

You index a text field with type autoEmbed. Atlas embeds existing and new documents with the chosen Voyage model, keeps the embeddings in sync, and embeds your query text at search time.

TypeScript
await knowledge().createSearchIndex({
  name: "knowledge_auto",
  type: "vectorSearch",
  definition: {
    fields: [
      { type: "autoEmbed", modality: "text", path: "text", model: "voyage-4" },
      { type: "filter", path: "tenantId" },
    ],
  },
});

const hits = await knowledge().aggregate([
  {
    $vectorSearch: {
      index: "knowledge_auto",
      path: "text",
      query: { text: "how do I reset my M-Pesa PIN?" },
      model: "voyage-4",
      numCandidates: 100,
      limit: 5,
      filter: { tenantId },
    },
  },
  { $project: { _id: 0, text: 1, source: 1, score: { $meta: "vectorSearchScore" } } },
]).toArray();
Model$ / 1M tokensUse
voyage-4-lite$0.02High volume, cost-sensitive
voyage-4$0.06Recommended general text
voyage-4-large$0.12Max accuracy
voyage-code-4$0.12Code / technical docs (Atlas only)
  • 200 million free tokens per model, once per Atlas organization. They don't refresh.
  • Query rate limits: an M0 cluster with no payment method gets 3 RPM / 2,000 TPM, which is demo-only. Paid clusters (M0 with a card, Flex, Dedicated) get 2,000 RPM, with TPM depending on the model.
  • M10+ needs storage auto-scaling enabled. If the disk fills, embedding pauses and the index goes Stale.
  • Generated vectors are stored on your cluster, in an internal database, and count toward storage (5 GB on Flex).
  • Changing model, numDimensions or quantization re-embeds everything (and bills again).
  • Create the index after bulk-loading. The first build uses a separate high-throughput path that isn't bound by rate limits.

B. Bring your own vectors (Embedding API)

Use this when you need the vectors elsewhere too (a cache, another store), or need explicit control. Create a model API key in Atlas (Voyage AI → API keys) and call https://ai.mongodb.com/v1/embeddings. Keys issued directly by Voyage AI use https://api.voyageai.com/v1/embeddings instead.

TypeScript
const res = await fetch("https://ai.mongodb.com/v1/embeddings", {
  method: "POST",
  headers: { Authorization: `Bearer ${process.env.VOYAGE_API_KEY}`, "Content-Type": "application/json" },
  body: JSON.stringify({ input: texts, model: "voyage-4", input_type: "document", output_dimension: 1024 }),
});

Index it as { "type": "vector", "path": "embedding", "numDimensions": 1024, "similarity": "dotProduct" } and query with queryVector. Use input_type: "document" for stored text and "query" for search text; Voyage says this markedly improves retrieval. Voyage 4-series embeddings (-lite, base, -large) are compatible with each other, so you can index with voyage-4-large and query with voyage-4-lite. Dimensions are 1024 by default, or 256/512/2048. The TypeScript SDK is voyageai (0.4.0); point it at Atlas with environment: "https://ai.mongodb.com/v1".

Which RAG store?

RAG storeWhen to choose
Neon + pgvector (house default for Postgres builds)Already on Postgres; vectors next to relational data; SQL filtering
Pinecone (house dedicated option)Large-scale, vector-first workloads; multi-tenant namespaces
MongoDB Vector SearchAlready on MongoDB; embeddings beside the source documents; Automated Embedding removes the embedding pipeline

Multi-tenant safety: always pass a filter (for example tenantId) in $vectorSearch, and index that path as a filter field. It's the same discipline as WHERE tenant_id = ….

MongoDB Search (formerly Atlas Search) adds full-text $search and hybrid search on the same cluster. It isn't compatible with Queryable Encryption.


Queryable Encryption (sensitive fields)

For fields the server must never see in plaintext (IDs, health data), Queryable Encryption encrypts on the client. The data stays encrypted at rest, in use, in logs and in backups, and still supports equality, range, prefix, suffix and substring queries. Prefix/suffix/substring need driver >= 7.5.0, mongodb-client-encryption >= 7.2.0 and MongoDB Server 9.0. Keys live in a KMS (AWS/Azure/GCP/KMIP). Driver 7.6 can route KMS calls through an HTTP proxy (kmsConnectCallback). It works on Atlas but not with MongoDB Search. Treat it as a design decision: decide at schema time, not after launch.

Atlas Data API and App Services are gone

The Data API and custom HTTPS Endpoints reached end of life on 2025-09-30, and Atlas App Services as a whole is EOL (only Triggers remain in the Atlas UI). There's no HTTP escape hatch for Edge or Workers. Call the database from a Node.js function, or use a Postgres/Neon path for edge-native code.


MongoDB MCP server in Claude Code

There are two servers. Pick one:

Atlas Managed MCP Server (remote)Local MCP (mongodb-mcp-server)
Claude Code plugin/plugin install mongodb-atlas@claude-plugins-official/plugin install mongodb@claude-plugins-official
AuthAtlas OAuth through /mcp → Authenticate (an org owner must enable AI Clients first)Connection string, Atlas service account, or Atlas Local (Docker)
RunsHosted by MongoDB; no local Nodenpx on your machine (Node ^20.19 || ^22.13 || >=24)
Best forAtlas clusters, team useSelf-managed / local dev, connection-string access

Useful tools (local server 3.1.0): find, aggregate, count, collection-schema, collection-indexes, explain, create-index, list-databases, export, atlas-list-clusters, atlas-get-performance-advisor, atlas-get-regions, atlas-local-create-deployment, search-knowledge.

Local server: safe manual setup

Run the interactive setup once. It writes a config file and asks about read-only mode, so answer Y:

Bash
npx mongodb-mcp-server@latest setup

Or register it yourself at user scope, after a global install (see fix 1 below; on native Windows use node + the package path as the command). Keep the connection string in your shell environment (from Hazina), not in the command line, and reference it with ${VAR} expansion in ~/.claude.json:

JSON
{
  "mcpServers": {
    "mongodb": {
      "type": "stdio",
      "command": "mongodb-mcp-server",
      "args": ["--readOnly"],
      "env": { "MDB_MCP_CONNECTION_STRING": "${MDB_MCP_CONNECTION_STRING}" }
    }
  }
}

Useful flags (or MDB_MCP_* env vars): --readOnly (only read/connect/metadata tools are registered), --indexCheck (rejects queries that would COLLSCAN), --disabledTools atlas or --disabledTools create update delete, --transport http --httpHost=0.0.0.0 (then connect to http://host:3000/mcp).

"connection timed out after 30000ms" — what's going on and how to fix it

On 2026-10-20, plugin:mongodb:mongodb timed out in the codeAmani Claude Code session. Here's the cause:

  • The mongodb plugin (1.2.1) starts the server with npx -y mongodb-mcp-server@<3. That resolves to 2.1.2, not 3.x, and npx has to download about 390 packages on a cold cache.
  • Measured on this Windows machine, installing 3.1.0 took 73 s, and a cold npx -y run passed 120 s. Claude Code's default MCP startup timeout is 30 s, so the first start always times out.
  • Once installed, the server answers the MCP initialize handshake almost instantly, even without a connection string (you can connect later with the connect tool). Missing credentials aren't the cause.

Fixes, in order of preference:

  1. Install the server once and point Claude Code at it (no npx on each start):
    Bash
    npm install -g mongodb-mcp-server@3.1.0
    # macOS / Linux / WSL
    claude mcp add mongodb --scope user -- mongodb-mcp-server --readOnly
    # Native Windows: run the package entry with node (avoids .cmd shim resolution)
    claude mcp add mongodb --scope user -- node "C:/Users/<you>/AppData/Roaming/npm/node_modules/mongodb-mcp-server/dist/esm/index.js" --readOnly
    npm root -g prints the global node_modules path if yours differs. Then turn off the plugin's own server (plugin:mongodb:mongodb) in /mcp, or disable the plugin in /plugin, so the slow npx copy doesn't keep timing out next to yours. Disabling the whole plugin also removes its mongodb-* skills.
  2. Or warm the npx cache so later cold starts are fast: npx -y "mongodb-mcp-server@<3" --version.
  3. Or raise the startup timeout for the session: export MCP_TIMEOUT=180000 (bash) or $env:MCP_TIMEOUT = "180000" (PowerShell) before starting claude.
  4. Or switch to the Atlas Managed MCP Server (mongodb-atlas plugin). It's remote, so there's nothing to download.

If it still fails: check node --version against the engines range, then read the logs at %LOCALAPPDATA%\mongodb\mongodb-mcp\.app-logs (Windows) or ~/.mongodb/mongodb-mcp/.app-logs. For HTTP transport, make sure the URL ends in /mcp. Atlas tools return "Atlas API credentials not configured" without MDB_MCP_API_CLIENT_ID / MDB_MCP_API_CLIENT_SECRET, and 403 if the service account's role is too low.

Safety: keep MCP sessions read-only against anything with client data. Writes through the MCP bypass Mongoose validation, so the collection $jsonSchema validator is your backstop. Never paste a connection string into chat; the docs warn specifically against runtime connect with production URIs.


Environment Variables

Only real secrets go below. The Vercel Marketplace integration injects MONGODB_URI for you.

Bash
# Atlas SRV connection string — server-only secret (contains the DB password, URL-encoded).
MONGODB_URI=mongodb+srv://app_user:URL%2DENCODED%2DPASS@cluster0.xxxxx.mongodb.net/app?retryWrites=true&w=majority&appName=acme-app

# Atlas model API key for the Voyage AI Embedding API (option B only; autoEmbed needs none).
VOYAGE_API_KEY=your-atlas-model-api-key

# MongoDB MCP server (local dev only) — never a production URI.
MDB_MCP_CONNECTION_STRING=mongodb+srv://readonly_user:...@cluster0.xxxxx.mongodb.net/
MDB_MCP_API_CLIENT_SECRET=your-atlas-service-account-secret

Non-secret settings:

VariableExamplePurpose
MONGODB_DBappDatabase name when it isn't in the URI path
MDB_MCP_API_CLIENT_ID<service-account-client-id>Atlas service-account ID (pairs with the secret above)
MDB_MCP_READ_ONLYtrueForce the MCP server into read-only mode
MCP_TIMEOUT180000Claude Code MCP startup timeout in ms (shell, not app)

MONGODB_URI, VOYAGE_API_KEY and the MCP secrets are server-only. Never use a NEXT_PUBLIC_* name for them, and store them in Hazina / Vercel env vars, not committed files.


Common Use Cases

Use CaseApproach
Default relational databaseNeon Postgres + Drizzle (house default). Use MongoDB only for true document needs
Semi-structured / occasional nestingPostgres jsonb on Neon before reaching for MongoDB
Flexible / evolving / per-tenant schemaMongoDB Atlas + Mongoose Schema.Types.Mixed
New project on VercelMarketplace native integration → MONGODB_URI injected
Connection on Vercel FluidModule-scoped client + attachDatabasePool + maxIdleTimeMS: 5000
Prototype / stagingFlex ($30/month cap). Free M0 only for demos
Kenya-targeted buildAtlas AF_SOUTH_1 + Vercel cpt1. Johannesburg is M10+ only
Input validationZod at the boundary + Mongoose schema + collection $jsonSchema
Analytics / joins / rollupsAggregation pipeline ($match → $lookup → $group → $project)
Atomic multi-document writessession.withTransaction(...)
Semantic search / RAG on Mongo dataVector Search with autoEmbed (voyage-4), or BYO Voyage vectors
Sensitive fields that must stay encryptedQueryable Encryption (driver 7.5+, Server 9.0 for string queries)
Inspect schema / indexes / run read queriesMongoDB MCP (--readOnly)

Troubleshooting

IssueFix
Atlas connection count climbs on VercelModule-scoped client + attachDatabasePool(client) + maxIdleTimeMS: 5000; never new MongoClient() per request
MongoParseError / auth failsURL-encode the password; check the DB user and its role
MongoServerSelectionError / timeoutAtlas IP access list must allow the host's egress (0.0.0.0/0 for Vercel; the Marketplace adds it)
OverwriteModelErrormodels.X ?? model("X", schema)
MongooseError: Operation buffering timed outbufferCommands: false and await dbConnect() before queries
Fails on Edge / WorkersDriver and Mongoose need Node.js; the Data API is EOL, so there's no HTTP fallback
Free cluster "throttled"M0 is 100 ops/s and 10 GB/7-day transfer. Move to Flex
$vectorSearch returns nothingIndex still building, or numDimensions doesn't match the model; for autoEmbed, check that the index isn't Stale (disk full)
context-limit-exceeded on $vectorSearchQuery text exceeds the model's 32K-token window
Automated Embedding queries rate-limitedM0 with no card gets 3 RPM; add a payment method or use Flex
Aggregation slow (COLLSCAN)Index the $match/$sort fields; confirm IXSCAN via explain
MCP "connection timed out after 30000ms"Cold npx download; install mongodb-mcp-server globally or raise MCP_TIMEOUT (see the MCP section)
TS error Cannot find module 'ws' from @vercel/functionsws is an optional peer; keep skipLibCheck: true (Next.js default) or add @types/ws

codeAmani notes

  • Database choice. MongoDB is a client-driven option, not a house default. Neon (then Supabase) wins unless the client needs a real document model. Record the reason in the project's README.
  • Keep the stack's defaults. Auth stays Clerk; payments stay Stripe. Store Stripe customer/subscription IDs on the user document, and verify Stripe webhook signatures before writing anything.
  • Secrets server-side only. MONGODB_URI, VOYAGE_API_KEY and MDB_MCP_* secrets live in Hazina / Vercel env vars. Replace the Marketplace's readWriteAnyDatabase user with a per-app readWrite user for client data.
  • AI routing. Claude stays primary for generation. Voyage (via Atlas) is the embedding provider when the data is in MongoDB, because it's billed on the same Atlas invoice and autoEmbed removes the embedding job. Start on voyage-4; drop to voyage-4-lite for high-volume indexing.
  • Kenya-targeted projects. Atlas AF_SOUTH_1 (Cape Town) + Vercel cpt1 is the default pair, and it works on Free/Flex. Johannesburg needs M10+. M-Pesa callback handlers: validate the callback, store CheckoutRequestID with a unique index right after the STK Push response, and deduplicate the callback with an upsert on that key. Amounts are integer KES. Mobile-first, low-bandwidth: project only the fields a screen needs.
  • Tier policy. Free M0 for demos only (it auto-pauses and has no backups). Flex for staging and small client apps. M10+ with backups for anything holding PHI/PII or payments.
  • MCP is for dev/test. Read-only against anything real. Prefer the Atlas Managed MCP Server for Atlas clusters, and install the local server globally instead of relying on npx cold starts.