Developing with MongoDB
The agent implements MongoDB NoSQL database solutions with document modeling, aggregation pipelines, and Mongoose ODM. Use when building document-based applications, designing schemas, writing aggregations, or implementing NoSQL patterns.
Works with
---
name: Developing with MongoDB
description: The agent implements MongoDB NoSQL database solutions with document modeling, aggregation pipelines, and Mongoose ODM. Use when building document-based applications, designing schemas, writing aggregations, or implementing NoSQL patterns.
license: MIT
---
# Developing with MongoDB
## Quick Start
```typescript
// Schema with Mongoose
import mongoose, { Schema, Document } from 'mongoose';
interface IUser extends Document {
email: string;
profile: { firstName: string; lastName: string };
createdAt: Date;
}
const userSchema = new Schema<IUser>({
email: { type: String, required: true, unique: true, lowercase: true },
profile: {
firstName: { type: String, required: true },
lastName: { type: String, required: true },
},
}, { timestamps: true });
userSchema.index({ email: 1 });
export const User = mongoose.model<IUser>('User', userSchema);
```
## Features
| Feature | Description | Guide |
|---------|-------------|-------|
| Document Schema | Type-safe schema design with Mongoose | Embed related data, use references for large collections |
| CRUD Operations | Create, read, update, delete with type safety | Use `findById`, `findOne`, `updateOne`, `deleteOne` |
| Aggregation Pipelines | Complex data transformations and analytics | Chain `$match`, `$group`, `$lookup`, `$project` stages |
| Indexing | Query optimization with proper indexes | Create compound indexes matching query patterns |
| Transactions | Multi-document ACID operations | Use sessions for operations requiring atomicity |
| Change Streams | Real-time data change notifications | Watch collections for inserts, updates, deletes |
## Common Patterns
### Repository Pattern with Pagination
```typescript
async findPaginated(filter: FilterQuery<IUser>, page = 1, limit = 20) {
const [data, total] = await Promise.all([
User.find(filter).sort({ createdAt: -1 }).skip((page - 1) * limit).limit(limit),
User.countDocuments(filter),
]);
return { data, pagination: { page, limit, total, totalPages: Math.ceil(total / limit) } };
}
```
### Aggregation Pipeline
```typescript
const stats = await Order.aggregate([
{ $match: { status: 'completed', createdAt: { $gte: startDate } } },
{ $group: { _id: '$userId', total: { $sum: '$amount' }, count: { $sum: 1 } } },
{ $sort: { total: -1 } },
{ $limit: 10 },
]);
```
### Transaction for Order Creation
```typescript
const session = await mongoose.startSession();
try {
session.startTransaction();
await Product.updateOne({ _id: productId }, { $inc: { stock: -quantity } }, { session });
const order = await Order.create([{ userId, items, total }], { session });
await session.commitTransaction();
return order[0];
} catch (error) {
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
```
## Best Practices
| Do | Avoid |
|----|-------|
| Design schemas based on query patterns | Embedding large arrays in documents |
| Create indexes for frequently queried fields | Using `$where` or mapReduce in production |
| Use `lean()` for read-only queries | Skipping validation on writes |
| Implement pagination for large datasets | Storing large files directly (use GridFS) |
| Set connection pool size appropriately | Hardcoding connection strings |
| Use transactions for multi-document ops | Ignoring index usage in explain plans |
| Add TTL indexes for expiring data | Creating too many indexes (write overhead) |More Database skills
supabase-postgres-best-practices
supabase/agent-skills
Postgres best practices maintained by Supabase, for Postgres running anywhere. Load this skill BEFORE writing or changing anything that lives in a Postgres database: creating or altering tables and columns (including choosing column types), schema design, migrations and declarative schema files, RLS policies and the tests that verify them, indexes, triggers, database functions, queues and scheduled jobs (pg_cron, pgmq), vector/semantic search (pgvector), and restoring dumps (pg_restore) or importing data. Also load it when diagnosing slow queries, high CPU, timeouts, EXPLAIN plans, connection exhaustion, locking, bloat, or rows visible to the wrong user or tenant. This is not just a performance guide — schema, migration, security, and SQL authoring tasks need these rules too, even for a one-column change or a single query.
prisma-database-setup
prisma/skills
Guides for configuring Prisma with different database providers (PostgreSQL, MySQL, SQLite, MongoDB, etc.). Use when setting up a new project, changing databases, or troubleshooting connection issues. Triggers on "configure postgres", "connect to mysql", "setup mongodb", "sqlite setup".
prisma-postgres
prisma/skills
Prisma Postgres setup and operations guidance across Console, create-db CLI, Management API, and Management API SDK. Use when creating Prisma Postgres databases, working in Prisma Console, provisioning with create-db/create-pg/create-postgres, or integrating programmatic provisioning with service tokens or OAuth.

