MongoDB Integration Guide

Technology: mongodb · Category: database · Last reviewed: 2026-10-20

Source: https://tech-stack.codeamanilabs.org/guide/mongodb

Insight:

MongoDB is advertised on motionstackstudios.com as a database option, but the house default is Neon Postgres + Drizzle (with Supabase as the second). Reach for MongoDB only on client projects that specifically require a document store — flexible/nested schemas, rapid prototyping, or a per-tenant variable shape. Before choosing it, consult the codeAmani-tech-stack MCP and confirm Postgres + jsonb won't do the job. On Vercel, provision through the Marketplace native integration (it injects MONGODB_URI) and register the module-scoped client with attachDatabasePool so Fluid compute doesn't leak Atlas connections. For Kenya-targeted builds, Atlas AF_SOUTH_1 (Cape Town) pairs with Vercel cpt1; Johannesburg is M10+ only.

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

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.

flowchart TD
    A["New client build<br/>needs a database"] --> B{"Flexible / nested /<br/>still-moving schema?"}
    B -->|No — relational shape| C["House default<br/>Neon Postgres + Drizzle"]
    B -->|"Maybe — semi-structured"| D{"Does Postgres jsonb<br/>cover it?"}
    D -->|Yes| C
    D -->|"No — true document model"| E["MongoDB Atlas<br/>(Vercel Marketplace or direct)"]
    E --> F["Mongoose schema<br/>+ Zod at the boundary"]
    F --> G["Module-scoped client<br/>+ attachDatabasePool"]
    G --> H["Aggregation · transactions<br/>· Vector Search (Voyage)"]

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

Resource URL
MongoDB Docs (root; append .md to any page for Markdown) https://www.mongodb.com/docs/
MongoDB Atlas (managed) https://www.mongodb.com/docs/atlas/
Node.js Driver (v7, current) https://www.mongodb.com/docs/drivers/node/current/
Node.js Driver release notes https://www.mongodb.com/docs/drivers/node/current/reference/release-notes/
Mongoose ODM (v9, current) https://mongoosejs.com/docs/
MongoDB Vector Search https://www.mongodb.com/docs/vector-search/
Voyage AI by MongoDB (Embedding & Reranking API) https://www.mongodb.com/docs/voyageai/
Atlas + Vercel native integration https://www.mongodb.com/docs/atlas/reference/partner-integrations/vercel/
@vercel/functions attachDatabasePool https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#database-connection-pool-management
MongoDB MCP Server https://www.mongodb.com/docs/mcp-server/
Pricing https://www.mongodb.com/pricing

Versions (verified on npm 2026-10-20)

Package Version Notes
mongodb (Node driver) 7.7.0 (2026-09-28) Node >= 20.19.0. v6 line still published as 6.21.0.
mongoose 9.11.2 (2026-10-12) Node >= 20.19.0. v8 maintained as 8.24.5.
@vercel/functions 3.10.1 Provides attachDatabasePool and waitUntil.
mongodb-mcp-server 3.1.0 (2026-10-15) Node ^20.19.0 || ^22.13.0 || >=24.0.0.
mongodb-client-encryption 7.2.1 Only for Queryable Encryption / CSFLE.
MongoDB Server 9.0 current stable Atlas 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:

Tier Price (Oct 2026) Storage Limits that matter Use for
Free (M0) $0 512 MB 100 ops/s, 500 connections, 10 GB in + 10 GB out per 7 days, no backups, auto-pauses after 30 idle days Learning, demos
Flex $0.011/hr, capped at $30/month up to 5 GB 500 ops/s, 500 connections, max 50 aggregation stages, no allowDiskUse, one daily snapshot, no private endpoints, no Performance Advisor Dev, staging, low-traffic client apps
Dedicated (M10+) from $0.08/hr (about $56.94/month for M10) 10 GB → 4 TB/node Full feature set; auto-scaling; 99.995% SLA Production, regulated data
Atlas Infinite (public preview) from $0.09/hr (about $65/month) up to 128 TB per HA shard M10+ only; decoupled compute and storage Spiky 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 region Provider / location Free Flex M10+
AF_SOUTH_1 AWS af-south-1, Cape Town ✅ ✅ ✅
SOUTH_AFRICA_NORTH Azure southafricanorth, Johannesburg — — ✅
AFRICA_SOUTH_1 Google Cloud africa-south1, Johannesburg — — ✅ (no Search Nodes)
SOUTH_AFRICA_WEST Azure southafricawest, Cape Town — — ✅

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:

What it does for you:

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.
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.

// 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:

flowchart LR
    A["Concurrent requests"] --> B["One Fluid instance<br/>(shared globals)"]
    B --> C["Module-scoped MongoClient<br/>maxPoolSize 10, maxIdleTimeMS 5000"]
    C --> D["Atlas cluster"]
    B -. "before suspend" .-> E["attachDatabasePool<br/>closes idle sockets"]
    F["new MongoClient() per request"] -.->|"pool exhaustion ✗"| G["Atlas refuses<br/>new connections"]

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

// 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.

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.

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.

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.

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 tokens Use
voyage-4-lite $0.02 High volume, cost-sensitive
voyage-4 $0.06 Recommended general text
voyage-4-large $0.12 Max accuracy
voyage-code-4 $0.12 Code / technical docs (Atlas only)

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.

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 store When 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 Search Already 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
Auth Atlas OAuth through /mcp → Authenticate (an org owner must enable AI Clients first) Connection string, Atlas service account, or Atlas Local (Docker)
Runs Hosted by MongoDB; no local Node npx on your machine (Node ^20.19 || ^22.13 || >=24)
Best for Atlas clusters, team use Self-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:

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:

{
  "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:

Fixes, in order of preference:

  1. Install the server once and point Claude Code at it (no npx on each start):
    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.

# 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:

Variable Example Purpose
MONGODB_DB app Database 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_ONLY true Force the MCP server into read-only mode
MCP_TIMEOUT 180000 Claude 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 Case Approach
Default relational database Neon Postgres + Drizzle (house default). Use MongoDB only for true document needs
Semi-structured / occasional nesting Postgres jsonb on Neon before reaching for MongoDB
Flexible / evolving / per-tenant schema MongoDB Atlas + Mongoose Schema.Types.Mixed
New project on Vercel Marketplace native integration → MONGODB_URI injected
Connection on Vercel Fluid Module-scoped client + attachDatabasePool + maxIdleTimeMS: 5000
Prototype / staging Flex ($30/month cap). Free M0 only for demos
Kenya-targeted build Atlas AF_SOUTH_1 + Vercel cpt1. Johannesburg is M10+ only
Input validation Zod at the boundary + Mongoose schema + collection $jsonSchema
Analytics / joins / rollups Aggregation pipeline ($match → $lookup → $group → $project)
Atomic multi-document writes session.withTransaction(...)
Semantic search / RAG on Mongo data Vector Search with autoEmbed (voyage-4), or BYO Voyage vectors
Sensitive fields that must stay encrypted Queryable Encryption (driver 7.5+, Server 9.0 for string queries)
Inspect schema / indexes / run read queries MongoDB MCP (--readOnly)

Troubleshooting

Issue Fix
Atlas connection count climbs on Vercel Module-scoped client + attachDatabasePool(client) + maxIdleTimeMS: 5000; never new MongoClient() per request
MongoParseError / auth fails URL-encode the password; check the DB user and its role
MongoServerSelectionError / timeout Atlas IP access list must allow the host's egress (0.0.0.0/0 for Vercel; the Marketplace adds it)
OverwriteModelError models.X ?? model("X", schema)
MongooseError: Operation buffering timed out bufferCommands: false and await dbConnect() before queries
Fails on Edge / Workers Driver 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 nothing Index still building, or numDimensions doesn't match the model; for autoEmbed, check that the index isn't Stale (disk full)
context-limit-exceeded on $vectorSearch Query text exceeds the model's 32K-token window
Automated Embedding queries rate-limited M0 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/functions ws is an optional peer; keep skipLibCheck: true (Next.js default) or add @types/ws

codeAmani notes

Official docs: