AI Skill Library

MongoDB Patterns

Document model, indexes, aggregation pipeline, schema design, transactions.

mongodbdatabasenosql
# MongoDB Patterns

## Embed vs Reference
- **Embed**: data accessed together, bounded size, owned by parent (1-to-few).
- **Reference**: large, shared, or unbounded data (1-to-many).

## CRUD
```ts
await col.insertOne({ name: 'A', tags: ['x'] })
await col.findOne({ _id: new ObjectId(id) })
await col.updateOne({ _id }, { $set: { name: 'B' }, $push: { tags: 'y' } })
await col.deleteOne({ _id })
```

## Update operators
`$set`, `$unset`, `$inc`, `$push`, `$pull`, `$addToSet`
- Atomic upsert: `findOneAndUpdate(..., { upsert: true, returnDocument: 'after' })`

## Indexes
```ts
col.createIndex({ email: 1 }, { unique: true })
col.createIndex({ createdAt: -1 })
col.createIndex({ title: 'text', body: 'text' }) // full-text
col.createIndex({ loc: '2dsphere' })             // geospatial
```
Use `explain('executionStats')` to verify index usage.

## Aggregation pipeline
```ts
db.orders.aggregate([
  { $match: { status: 'paid' } },
  { $group: { _id: '$userId', total: { $sum: '$amount' } } },
  { $sort: { total: -1 } },
  { $limit: 10 },
  { $lookup: { from: 'users', localField: '_id', foreignField: '_id', as: 'user' } },
])
```

## Transactions
```ts
const session = client.startSession()
await session.withTransaction(async () => {
  await orders.insertOne({ ... }, { session })
  await inventory.updateOne({ ... }, { $inc: { qty: -1 } }, { session })
})
```

## Schema patterns
- **Bucket**: group time-series into buckets
- **Computed**: cache expensive calculations on document
- **Polymorphic**: different shapes in one collection with a discriminator field

API: /api/skills/mongodb-patterns