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
agents-inc-skills
24200 skills
Install
$ npx -y skills add agents-inc/skills --skill api-database-mongodb --agent claude-code

How it fires

How this skill gets triggered: by you, by Claude, or both.

  • Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.Auto-invocation is when the right skill fires by itself at the right moment, driven by a FLOW.md router and a hook, instead of you invoking it by name. It is the difference between a skill being installed and a skill actually getting used.Read the full definition →
  • You can call itInvoke it directly when you want it.
  • Slash command/api-database-mongodb

Context preview

The summary Claude sees to decide when to auto-load this skill.

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

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

> **All code must follow project conventions in CLAUDE.md** (kebab-case, named exports, import ordering, `import type`, named constants)

**(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 res

Read more
Ships withagents-inc-skills

The official skills marketplace for Agents Inc. 150+ 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?

Get the whole plugin

Other skills on agents-inc-skills.