mongodb
Work with MongoDB databases using best practices. Use when designing schemas, writing queries, building aggregation pipelines, or optimizing performance. Triggers on MongoDB, Mongoose, NoSQL, aggregation pipeline, document database, MongoDB Atlas.
What this skill does
# MongoDB & Mongoose
Build and query MongoDB databases with best practices.
## Quick Start
```bash
npm install mongodb mongoose
```
### Native Driver
```typescript
import { MongoClient, ObjectId } from 'mongodb';
const client = new MongoClient(process.env.MONGODB_URI!);
const db = client.db('myapp');
const users = db.collection('users');
// Connect
await client.connect();
// CRUD Operations
await users.insertOne({ name: 'Alice', email: '[email protected]' });
const user = await users.findOne({ email: '[email protected]' });
await users.updateOne({ _id: user._id }, { $set: { name: 'Alice Smith' } });
await users.deleteOne({ _id: user._id });
```
### Mongoose Setup
```typescript
import mongoose from 'mongoose';
await mongoose.connect(process.env.MONGODB_URI!, {
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
});
// Connection events
mongoose.connection.on('connected', () => console.log('MongoDB connected'));
mongoose.connection.on('error', (err) => console.error('MongoDB error:', err));
mongoose.connection.on('disconnected', () => console.log('MongoDB disconnected'));
// Graceful shutdown
process.on('SIGINT', async () => {
await mongoose.connection.close();
process.exit(0);
});
```
## Schema Design
### Basic Schema
```typescript
import mongoose, { Schema, Document, Model } from 'mongoose';
interface IUser extends Document {
email: string;
name: string;
password: string;
role: 'user' | 'admin';
profile: {
avatar?: string;
bio?: string;
};
createdAt: Date;
updatedAt: Date;
}
const userSchema = new Schema<IUser>({
email: {
type: String,
required: [true, 'Email is required'],
unique: true,
lowercase: true,
trim: true,
match: [/^\S+@\S+\.\S+$/, 'Invalid email format'],
},
name: {
type: String,
required: true,
trim: true,
minlength: 2,
maxlength: 100,
},
password: {
type: String,
required: true,
select: false, // Never return password by default
},
role: {
type: String,
enum: ['user', 'admin'],
default: 'user',
},
profile: {
avatar: String,
bio: { type: String, maxlength: 500 },
},
}, {
timestamps: true, // Adds createdAt, updatedAt
toJSON: {
transform(doc, ret) {
delete ret.password;
delete ret.__v;
return ret;
},
},
});
// Indexes
userSchema.index({ email: 1 });
userSchema.index({ createdAt: -1 });
userSchema.index({ name: 'text', 'profile.bio': 'text' }); // Text search
const User: Model<IUser> = mongoose.model('User', userSchema);
```
### Embedded Documents vs References
```typescript
// ✅ Embed when: Data is read together, doesn't grow unbounded
const orderSchema = new Schema({
customer: {
name: String,
email: String,
address: {
street: String,
city: String,
country: String,
},
},
items: [{
product: String,
quantity: Number,
price: Number,
}],
total: Number,
});
// ✅ Reference when: Data is large, shared, or changes independently
const postSchema = new Schema({
title: String,
content: String,
author: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
comments: [{
type: Schema.Types.ObjectId,
ref: 'Comment',
}],
});
// Populate references
const post = await Post.findById(id)
.populate('author', 'name email') // Select specific fields
.populate({
path: 'comments',
populate: { path: 'author', select: 'name' }, // Nested populate
});
```
### Virtuals
```typescript
const userSchema = new Schema({
firstName: String,
lastName: String,
});
// Virtual field (not stored in DB)
userSchema.virtual('fullName').get(function() {
return `${this.firstName} ${this.lastName}`;
});
// Virtual populate (for reverse references)
userSchema.virtual('posts', {
ref: 'Post',
localField: '_id',
foreignField: 'author',
});
// Enable virtuals in JSON
userSchema.set('toJSON', { virtuals: true });
userSchema.set('toObject', { virtuals: true });
```
## Query Operations
### Find Operations
```typescript
// Find with filters
const users = await User.find({
role: 'user',
createdAt: { $gte: new Date('2024-01-01') },
});
// Query builder
const results = await User.find()
.where('role').equals('user')
.where('createdAt').gte(new Date('2024-01-01'))
.select('name email')
.sort({ createdAt: -1 })
.limit(10)
.skip(20)
.lean(); // Return plain objects (faster)
// Find one
const user = await User.findOne({ email: '[email protected]' });
const userById = await User.findById(id);
// Exists check
const exists = await User.exists({ email: '[email protected]' });
// Count
const count = await User.countDocuments({ role: 'admin' });
```
### Query Operators
```typescript
// Comparison
await User.find({ age: { $eq: 25 } }); // Equal
await User.find({ age: { $ne: 25 } }); // Not equal
await User.find({ age: { $gt: 25 } }); // Greater than
await User.find({ age: { $gte: 25 } }); // Greater or equal
await User.find({ age: { $lt: 25 } }); // Less than
await User.find({ age: { $lte: 25 } }); // Less or equal
await User.find({ age: { $in: [20, 25, 30] } }); // In array
await User.find({ age: { $nin: [20, 25] } }); // Not in array
// Logical
await User.find({
$and: [{ age: { $gte: 18 } }, { role: 'user' }],
});
await User.find({
$or: [{ role: 'admin' }, { isVerified: true }],
});
await User.find({ age: { $not: { $lt: 18 } } });
// Element
await User.find({ avatar: { $exists: true } });
await User.find({ score: { $type: 'number' } });
// Array
await User.find({ tags: 'nodejs' }); // Array contains value
await User.find({ tags: { $all: ['nodejs', 'mongodb'] } }); // Contains all
await User.find({ tags: { $size: 3 } }); // Array length
await User.find({ 'items.0.price': { $gt: 100 } }); // Array index
// Text search
await User.find({ $text: { $search: 'mongodb developer' } });
// Regex
await User.find({ name: { $regex: /^john/i } });
```
### Update Operations
```typescript
// Update one
await User.updateOne(
{ _id: userId },
{ $set: { name: 'New Name' } }
);
// Update many
await User.updateMany(
{ role: 'user' },
{ $set: { isVerified: true } }
);
// Find and update (returns document)
const updated = await User.findByIdAndUpdate(
userId,
{ $set: { name: 'New Name' } },
{ new: true, runValidators: true } // Return updated doc, run validators
);
// Update operators
await User.updateOne({ _id: userId }, {
$set: { name: 'New Name' }, // Set field
$unset: { tempField: '' }, // Remove field
$inc: { loginCount: 1 }, // Increment
$mul: { score: 1.5 }, // Multiply
$min: { lowScore: 50 }, // Set if less than
$max: { highScore: 100 }, // Set if greater than
$push: { tags: 'new-tag' }, // Add to array
$pull: { tags: 'old-tag' }, // Remove from array
$addToSet: { tags: 'unique-tag' }, // Add if not exists
});
// Upsert (insert if not exists)
await User.updateOne(
{ email: '[email protected]' },
{ $set: { name: 'New User' } },
{ upsert: true }
);
```
## Aggregation Pipeline
### Basic Aggregation
```typescript
const results = await Order.aggregate([
// Stage 1: Match
{ $match: { status: 'completed' } },
// Stage 2: Group
{ $group: {
_id: '$customerId',
totalOrders: { $sum: 1 },
totalSpent: { $sum: '$total' },
avgOrder: { $avg: '$total' },
}},
// Stage 3: Sort
{ $sort: { totalSpent: -1 } },
// Stage 4: Limit
{ $limit: 10 },
]);
```
### Pipeline Stages
```typescript
const pipeline = [
// $match - Filter documents
{ $match: { createdAt: { $gte: new Date('2024-01-01') } } },
// $project - Shape output
{ $project: {
name: 1,
email: 1,
yearJoined: { $year: '$createdAt' },
fullName: { $concat: ['$firstName', ' ', '$lastName'] },
}},
// $lookup - Join collections
{ $lookup: {
from: 'orders',
localField: '_id'Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.