mongodb
MongoDB fundamentals including document model, CRUD operations, querying, indexing, and aggregation framework for NoSQL database applications.
What this skill does
# MongoDB Mastery
## Document Model Basics
```javascript
// MongoDB document (JSON-like structure)
{
_id: ObjectId("507f1f77bcf86cd799439011"),
firstName: "John",
lastName: "Doe",
email: "[email protected]",
salary: 75000,
department: "Engineering",
skills: ["JavaScript", "Python", "SQL"],
address: {
street: "123 Main St",
city: "New York",
state: "NY"
},
joinDate: new Date("2023-01-15")
}
```
## Collection Operations
```javascript
// Create database and collection
use company_db
// Insert single document
db.employees.insertOne({
firstName: "Jane",
lastName: "Smith",
email: "[email protected]",
salary: 80000
})
// Insert multiple documents
db.employees.insertMany([
{ firstName: "Bob", lastName: "Johnson", salary: 70000 },
{ firstName: "Alice", lastName: "Williams", salary: 85000 }
])
// Get document count
db.employees.countDocuments({})
// Validate collection
db.employees.validate()
```
## CRUD Operations
```javascript
// READ - Basic find
db.employees.find()
// Find by condition
db.employees.find({ salary: { $gt: 75000 } })
// Find with projection (select specific fields)
db.employees.find(
{ department: "Engineering" },
{ firstName: 1, lastName: 1, salary: 1, _id: 0 }
)
// Find one document
db.employees.findOne({ email: "[email protected]" })
// UPDATE - Update one document
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $set: { salary: 90000 } }
)
// Update multiple documents
db.employees.updateMany(
{ department: "Engineering" },
{ $set: { bonus: 5000 } }
)
// DELETE - Delete documents
db.employees.deleteOne({ _id: ObjectId("...") })
db.employees.deleteMany({ department: "HR" })
```
## Query Operators
```javascript
// Comparison operators
db.employees.find({ salary: { $gt: 75000 } }) // Greater than
db.employees.find({ salary: { $gte: 75000 } }) // Greater than or equal
db.employees.find({ salary: { $lt: 75000 } }) // Less than
db.employees.find({ salary: { $lte: 75000 } }) // Less than or equal
db.employees.find({ salary: { $eq: 75000 } }) // Equal
db.employees.find({ salary: { $ne: 75000 } }) // Not equal
// Array operators
db.employees.find({ skills: "JavaScript" }) // Contains value
db.employees.find({ skills: { $in: ["Python", "Go"] } }) // Contains any
db.employees.find({ skills: { $all: ["JavaScript", "Python"] } }) // Contains all
db.employees.find({ skills: { $size: 3 } }) // Array size
// Element operators
db.employees.find({ phone: { $exists: true } }) // Field exists
db.employees.find({ salary: { $type: "number" } }) // Field type check
// String matching
db.employees.find({ email: { $regex: "gmail" } }) // Regular expression
```
## Sorting and Limiting
```javascript
// Sort by single field
db.employees.find().sort({ salary: -1 }) // Descending
db.employees.find().sort({ salary: 1 }) // Ascending
// Sort by multiple fields
db.employees.find().sort({ department: 1, salary: -1 })
// Limit and skip
db.employees.find().limit(10) // First 10 results
db.employees.find().skip(20).limit(10) // Pagination
```
## Indexing
```javascript
// Create single field index
db.employees.createIndex({ email: 1 })
// Create unique index
db.employees.createIndex({ email: 1 }, { unique: true })
// Create compound index
db.employees.createIndex({ department: 1, salary: -1 })
// Create text index for search
db.employees.createIndex({ firstName: "text", lastName: "text" })
// List indexes
db.employees.getIndexes()
// Drop index
db.employees.dropIndex("email_1")
// Full text search with text index
db.employees.find({ $text: { $search: "john" } })
```
## Data Types
```javascript
// String
{ name: "John Doe" }
// Number (Int32, Int64, Double)
{ age: 30, salary: 75000.50 }
// Boolean
{ active: true }
// Date
{ createdDate: new Date() }
// Array
{ skills: ["JavaScript", "Python"] }
// Object/Embedded document
{ address: { city: "NYC", state: "NY" } }
// ObjectID
{ _id: ObjectId() }
// Null
{ phone: null }
// Regular Expression
{ email: /gmail/ }
```
## Bulk Operations
```javascript
// Initialize bulk operation
let bulk = db.employees.initializeUnorderedBulkOp()
// Add multiple operations
bulk.find({ department: "Engineering" }).update({ $set: { bonus: 5000 } })
bulk.find({ salary: { $lt: 50000 } }).update({ $inc: { salary: 2000 } })
bulk.insert({ firstName: "New", lastName: "Employee" })
bulk.find({ _id: ObjectId("...") }).removeOne()
// Execute bulk
bulk.execute()
```
## Aggregation Pipeline (Data Processing)
```javascript
// Basic pipeline stages
db.employees.aggregate([
{ $match: { salary: { $gt: 75000 } } }, // Filter
{ $group: { // Group & aggregate
_id: "$department",
avgSalary: { $avg: "$salary" },
count: { $sum: 1 }
}},
{ $sort: { avgSalary: -1 } }, // Sort
{ $limit: 5 } // Limit results
])
// Projection stage (reshape documents)
db.employees.aggregate([
{ $project: {
fullName: { $concat: ["$firstName", " ", "$lastName"] },
salary: 1,
yearing_salary: { $multiply: ["$salary", 12] },
_id: 0
}}
])
// Unwind arrays for analysis
db.employees.aggregate([
{ $unwind: "$skills" }, // Expand skills array
{ $group: {
_id: "$skills",
count: { $sum: 1 }
}},
{ $sort: { count: -1 } }
])
// Lookup (similar to SQL JOIN)
db.orders.aggregate([
{ $lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customerInfo"
}},
{ $unwind: "$customerInfo" },
{ $project: {
orderId: 1,
"customerInfo.name": 1,
"customerInfo.email": 1,
amount: 1
}}
])
// Complex multi-stage pipeline
db.sales.aggregate([
{ $match: { date: { $gte: new Date("2023-01-01") } } },
{ $group: {
_id: { month: { $month: "$date" }, year: { $year: "$date" } },
totalSales: { $sum: "$amount" },
avgSale: { $avg: "$amount" },
ordersCount: { $sum: 1 }
}},
{ $sort: { "_id.year": 1, "_id.month": 1 } },
{ $project: {
month: "$_id.month",
year: "$_id.year",
totalSales: { $round: ["$totalSales", 2] },
avgSale: { $round: ["$avgSale", 2] },
ordersCount: 1,
_id: 0
}}
])
```
## Transactions (ACID)
```javascript
// Start a session
const session = db.getMongo().startSession()
session.startTransaction()
try {
// Multiple operations in transaction
db.accounts.updateOne(
{ _id: "account1" },
{ $inc: { balance: -100 } },
{ session: session }
)
db.accounts.updateOne(
{ _id: "account2" },
{ $inc: { balance: 100 } },
{ session: session }
)
// All succeed or all fail
session.commitTransaction()
} catch (error) {
session.abortTransaction()
throw error
} finally {
session.endSession()
}
```
## Update Operators
```javascript
// $set - set field value
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $set: { salary: 90000 } }
)
// $inc - increment field
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $inc: { salary: 5000 } }
)
// $push - add to array
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $push: { skills: "Kubernetes" } }
)
// $addToSet - add to array if not exists
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $addToSet: { skills: "Docker" } }
)
// $pull - remove from array
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $pull: { skills: "COBOL" } }
)
// $unset - remove field
db.employees.updateOne(
{ _id: ObjectId("...") },
{ $unset: { phone: "" } }
)
// Combination updates
db.employees.updateOne(
{ _id: ObjectId("...") },
{
$set: { updatedAt: new Date() },
$inc: { salary: 5000 },
$push: { performanceRatings: 4.5 }
}
)
```
## Array Queries
```javascript
// Query array elements
db.employees.find({ skills: "Python" }) // Has Python skill
// Query array with conditions
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.