mongodb

Guidance for using MongoDB, a database that stores records as flexible documents, from asynchronous Python code with Motor. It covers database queries, data grouping, indexes, transactions, live change feeds, and document design.

In plain words
What is it for?
Use it to write async database operations, build aggregation pipelines, create indexes, run multi-record transactions, watch changes, or store task state.
Why use it?
It helps avoid common mistakes when retrieving, organizing, searching, and safely changing MongoDB data in programs that perform other work while waiting for the database.

Skill for Claude CodeCodex

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add skills/kid-sid/codex-spellbook/mongodb
Any agent
npx skills add kid-sid/codex-spellbook --skill mongodb
Clone the repo
git clone --depth 1 https://github.com/kid-sid/codex-spellbook

Made for: Claude Code, Codex.

Per session 35 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 4,741 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00035 $0.04741
Opus 5 $0.00017 $0.02371
Sonnet 5 $0.00007 $0.00948
Haiku 4.5 $0.00003 $0.00474

Measured 3d ago against content hash 0aaa5375adfb, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

mongodb scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 3d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

skills/mongodb/SKILL.md · 573 lines

How it starts

The opening of the file, as written. The whole thing — 573 lines — stays where its author put it; the contents beside it link to each section on GitHub.

MongoDB — Async Patterns with Motor

Async MongoDB via Motor, aggregation pipelines, and index design.

When to Activate

  • Writing async MongoDB queries with Motor
  • Designing aggregation pipelines ($match, $group, $lookup, $unwind)
  • Creating indexes (compound, text, TTL, sparse, partial)
  • Running multi-document transactions
  • Watching for real-time changes with change streams
  • Working with adk.state (Agentex per-task state backed by MongoDB)
  • Designing document schemas for flexible or hierarchical data

Connection

from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase

client = AsyncIOMotorClient("mongodb://localhost:27017")
db: AsyncIOMotorDatabase = client["mydb"]

# With auth + replica set (production)
client = AsyncIOMotorClient(
    "mongodb://user:pass@host1:27017,host2:27017/mydb?replicaSet=rs0&authSource=admin"
)

# Close on shutdown
client.close()

Collections are accessed as attributes — no schema declaration needed:

users = db["users"]              # or db.users
orders = db.orders

CRUD

from datetime import datetime, timezone
from bson import ObjectId

# Insert one
result = await db.users.insert_one({
    "email": "[email protected]",
    "name": "Alice",
    "role": "user",
    "created_at": datetime.now(timezone.utc),
})
inserted_id = result.inserted_id   # ObjectId

# Insert many
result = await db.users.insert_many([
    {"email": "[email protected]", "name": "Bob"},
    {"email": "[email protected]", "name": "Carol"},
])

# Find one
user = await db.users.find_one({"email": "[email protected]"})
user = await db.users.find_one({"_id": ObjectId("64a...")})

# Find many — returns an async cursor
cursor = db.users.find({"role": "admin"}).sort("created_at", -1).skip(0).limit(20)
users = await cursor.to_list(length=None)   # length=None = all results

# Count
count = await db.users.count_documents({"role": "admin"})
estimated = await db.users.estimated_document_count()   # fast, uses metadata

# Update one
result = await db.users.update_one(
    {"_id": ObjectId("64a...")},
    {"$set": {"role": "admin", "updated_at": datetime.now(timezone.utc)}},
)
matched = result.matched_count
modified = result.modified_count

# Update many
await db.users.update_many(
    {"role": "user", "created_at": {"$lt": cutoff_date}},
    {"$set": {"tier": "legacy"}},
)

# Upsert
await db.users.update_one(
    {"email": "[email protected]"},
    {"$setOnInsert": {"created_at": datetime.now(timezone.utc)},
     "$set": {"name": "Dave", "role": "user"}},
    upsert=True,
)

# Delete
await db.users.delete_one({"_id": ObjectId("64a...")})
await db.users.delete_many({"status": "inactive", "created_at": {"$lt": cutoff}})

# Find one and update (atomic — returns updated doc)
updated = await db.users.find_one_and_update(
    {"_id": ObjectId("64a...")},
    {"$inc": {"login_count": 1}},
    return_document=True,    # return doc after update
)

Read the full file on GitHub · 573 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 3d ago First seen · 573 lines · 35 tokens per session scan A 0aaa5375adfb

Subscribe to this mod's changes

mongodb is a skill published in the GitHub repository kid-sid/codex-spellbook (21 stars, last pushed 3mo ago), licensed MIT. It adds 35 tokens to every session and 4,741 once invoked, about $0.0002 per session on Opus 5. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.

Related

Other skills, from other repositories

azure-mgmt-mongodbatlas-dotnet

Manage MongoDB Atlas Organizations as Azure ARM resources using Azure.ResourceManager.MongoDBAtlas SDK. Use when creating, updating, listing, or deleting MongoDB Atlas organizations through Azure Marketplace integration. This SDK manages the Azure-side organization resource, not Atlas clusters/databases directly.

microsoft/skills · 64 tokens

moai-domain-database

Database specialist covering PostgreSQL, MongoDB, Redis, Oracle, and cloud database platforms (Neon, Supabase, Firestore). Use for schema design, query optimization, indexing strategies, data modeling, or cloud database selection. Cloud vendor guide absorbed from moai-platform-database-cloud.

modu-ai/moai-adk · 64 tokens

mongodb-mcp-v3-migration

Migrates external consumer code from the mongodb-mcp-server v1/v2 single-package API to the v3 scoped-package structure. In v3, mongodb-mcp-server is a binary-only package (npx / MCPB); library embedding uses @mongodb-js/mcp-cli, @mongodb-js/mcp-core, @mongodb-js/mcp-http-runners, @mongodb-js/mcp-tools-, and the other…

mongodb-js/mongodb-mcp-server · 153 tokens

prisma-mongodb-upgrade

Decision and migration guide for Prisma ORM MongoDB projects on v6, which have no upgrade path to v7. Use when a MongoDB project asks about upgrading Prisma, when "upgrade to prisma 7" comes up in a project with provider = "mongodb", or when evaluating a move to Prisma Next. Triggers on "upgrade prisma mongodb"…

nitrocloudofficial/nitrostack · 95 tokens

mongodb

MongoDB operations expert for queries, aggregation pipelines, indexes, and schema design.

RightNow-AI/openfang · 17 tokens

mongodb-atlas-stream-processing

Manages MongoDB Atlas Stream Processing (ASP) workflows. Handles workspace provisioning, data source/sink connections, processor lifecycle operations, debugging diagnostics, and tier sizing. Supports Kafka, Atlas clusters, S3, HTTPS, and Lambda integrations for streaming data workloads and event processing. NOT for…

fcakyon/claude-codex-settings · 82 tokens