Skip to content
Development
Skill

/api-database-mongodb

Native MongoDB driver (the mongodb npm package) - MongoClient lifecycle, typed collections, CRUD result shapes, cursors, aggregation pipelines, index design, transactions

From plugin
skills
26200 skills

Claude Code

$ npx -y skills add agents-inc/skills --skill api-database-mongodb --agent claude-code

SKILL.md

api-database-mongodb.SKILL.md
name: api-database-mongodb
description: Native MongoDB driver (the mongodb npm package) - MongoClient lifecycle, typed collections, CRUD result shapes, cursors, aggregation pipelines, index design, transactions

MongoDB Native Driver Patterns

> **Quick Guide:** Talk to MongoDB through the official `mongodb` driver with no schema layer in between. Create ONE `MongoClient` per process and reuse it -- it owns the connection pool. Type collections with a generic: `db.collection<UserDoc>("users")`. Write operations return acknowledgements, never documents. `find()` returns a lazy cursor; stream it with `for await` instead of `toArray()` for anything unbounded. Put `$match` first in every pipeline so it can use an index. Verify indexes with `explain("executionStats")` rather than assuming. Transactions need a replica set, a session on every operation, and a callback that can safely run twice.

---

<critical_requirements>

CRITICAL: Before Using This Skill

**(You MUST create exactly ONE `MongoClient` per process and reuse it -- the client owns a connection pool, so constructing one per request opens a new pool per request and exhausts the server's connection limit)**

**(You MUST pass `{ session }` to EVERY operation inside a transaction -- an operation without it silently runs outside the transaction and is not rolled back)**

**(You MUST write `withTransaction` callbacks to be safely re-runnable -- the driver retries them on transient errors, so any side effect outside the transaction happens more than once)**

**(You MUST iterate or close every cursor you open -- an abandoned cursor holds server-side resources until it times out)**

**(You MUST NOT expect write operations to return documents -- `insertOne` returns `{ acknowledged, insertedId }` and `updateOne` returns counts; only the `findOneAnd*` family returns a document)**

**(You MUST verify a query uses the index you intended with `explain("executionStats")` -- an unindexed query succeeds silently and only fails once the collection is large)**

</critical_requirements>

---

**Auto-detection:** mongodb, MongoClient, ServerApiVersion, client.db, db.collection, insertOne, insertMany, updateOne, findOneAndUpdate, deleteOne, bulkWrite, FindCursor, AggregationCursor, toArray, ObjectId, WithId, OptionalUnlessRequiredId, Filter, UpdateFilter, createIndex, createIndexes, explain, startSession, withTransaction, readPreference, writeConcern, maxPoolSize, serverSelectionTimeoutMS, MongoServerError, code 11000

**When to use:**

  • Talking to MongoDB directly with no schema or modelling layer in between
  • Aggregation-heavy workloads (reporting, analytics, materialised views)
  • Bulk and batch pipelines where per-document overhead is the bottleneck
  • Index design, query-plan investigation, and performance work
  • Multi-document transactions with explicit session control
  • Serverless and edge runtimes where client and pool lifecycle must be controlled by hand

**Key patterns covered:**

  • Client and pool lifecycle (one client per process, startup and shutdown, serverless reuse)
  • Typed collections and the driver's document type helpers
  • CRUD and the result shapes each operation actually returns
  • Cursors: lazy evaluation, streaming, batching, and pagination that stays fast
  • Aggregation pipeline construction, stage ordering, and memory limits
  • Index types, compound key ordering, and verification with `explain`
  • Transactions: sessions, retry semantics, and when not to use one
  • Error handling on driver-specific error codes

**When NOT to use:**

  • You want schemas, validation, middleware hooks or population handled for you -- use an ODM layer instead of building one on top of this
  • Highly relational data with multi-table joins and foreign key constraints (use a relational database)
  • Simple key-value caching (use a dedicated key-value store)
  • Time-series data at very large scale (use a purpose-built time-series database)

**Detailed Resources:**

  • For decision tables, connection-option reference, and operator lookup, see [reference.md](reference.md)

**Core Patterns:**

  • [examples/core.md](examples/core.md) - Client lifecycle, typed collections, CRUD and result shapes, error handling

**Query Patterns:**

  • [examples/queries.md](examples/queries.md) - Filters, projection, cursors, streaming, keyset pagination, counting

**Aggregation:**

  • [examples/aggregation.md](examples/aggregation.md) - Pipeline construction, `$lookup`, `$facet`, `$merge`, typed output

**Indexing:**

  • [examples/indexes.md](examples/indexes.md) - Single-field, compound (ESR), partial, TTL, text, geospatial, and `explain`

**Advanced Patterns:**

  • [examples/patterns.md](examples/patterns.md) - Transactions, bulk writes, change streams, schema evolution, serverless

---

<philosophy>

Philosophy

The native driver is a thin, faithful mapping of the MongoDB wire protocol into TypeScript. It gives you the database's own vocabulary -- commands, cursors, pipelines, sessions -- with nothing interpreting them on your behalf. **Its value is that nothing is hidden, and its cost is that nothing is provided.** There is no schema, no validation, no lifecycle hook, no lazy reference resolution. Whatever structure your documents have is the structure your code maintains.

That trade is worth making when the database's own model is the thing you are working with: aggregation pipelines, index behaviour, bulk throughput, transaction boundaries. It is a poor trade when what you actually wanted was application-layer modelling, because building a half-schema by hand is strictly worse than adopting one.

**Core principles:**

1. **One client, one pool, one process.** `MongoClient` is a long-lived object that manages a pool of sockets. Creating one per request is the single most expensive mistake available here, and it looks like correct resource hygiene while doing the opposite. 2. **The driver returns what the server returned.** Write commands return acknowledgements and cou

Read more
@agents-inc
Ships withskills

The official skills marketplace for Agents Inc. 230+ skills covering everything from React and Prisma to Redis, ElevenLabs, and infrastructure tooling. Pick the skills that match your stack and install them via Claude Code. Need more control?

Stars on GitHub

Momentum

stars in total
26
Star history of agents-inc/skills on GitHub, a chart by star-history.com

Other skills on skills.

ai-infrastructure-litellm

ai-infrastructure-lite…

LiteLLM proxy server setup, TypeScript client patterns via OpenAI SDK, model routing, fallbacks, load balancing, spend tracking,…

@agents-inc@agents-incInstall Skill
ai-infrastructure-modal

ai-infrastructure-moda…

Serverless GPU compute platform for AI model deployment — web endpoints, GPU functions, model serving, and TypeScript client…

@agents-inc@agents-incInstall Skill
ai-infrastructure-ollama

ai-infrastructure-olla…

Local LLM inference with the Ollama JavaScript client -- chat, streaming, tool calling, vision, embeddings, structured output,…

@agents-inc@agents-incInstall Skill

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills10d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc12d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react1d252k
@facebook@facebookInstall Skill

Questions about api-database-mongodb.

Which coding agents can use api-database-mongodb?
api-database-mongodb installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.