mongodb
БесплатноБез исполняемых скриптовНе проверенMongoDB document database. Covers CRUD operations, aggregations, and indexes. Use when working with MongoDB. USE WHEN: user mentions "mongodb", "mongo"…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
MongoDB Core Knowledge
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:mongodbfor comprehensive documentation.
CRUD Operations
// Create
db.users.insertOne({
name: "John",
email: "[email protected]",
createdAt: new Date()
});
// Read
db.users.find({ isActive: true })
.sort({ createdAt: -1 })
.limit(20);
db.users.findOne({ _id: ObjectId("...") });
// Update
db.users.updateOne(
{ _id: ObjectId("...") },
{ $set: { name: "Jane" } }
);
// Delete
db.users.deleteOne({ _id: ObjectId("...") });
Query Operators
// Comparison
{ age: { $gt: 18, $lt: 65 } }
{ status: { $in: ["active", "pending"] } }
// Logical
{ $and: [{ age: { $gt: 18 } }, { isActive: true }] }
{ $or: [{ status: "admin" }, { role: "moderator" }] }
// Array
{ tags: { $all: ["tech", "news"] } }
{ "scores.0": { $gt: 90 } }
Aggregation Pipeline
db.orders.aggregate([
{ $match: { status: "completed" } },
{ $group: {
_id: "$userId",
totalSpent: { $sum: "$amount" },
orderCount: { $count: {} }
}},
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
]);
Indexes
db.users.createIndex({ email: 1 }, { unique: true });
db.users.createIndex({ createdAt: -1 });
db.users.createIndex({ name: "text" }); // Text search
Production Readiness
Security Configuration
// Enable authentication (mongod.conf)
// security:
// authorization: enabled
// Create admin user
use admin
db.createUser({
user: "admin",
pwd: "secure_password",
roles: ["root"]
});
// Create application user with limited privileges
use mydb
db.createUser({
user: "app_user",
pwd: "app_password",
roles: [
{ role: "readWrite", db: "mydb" }
]
});
// Create read-only user for reporting
db.createUser({
user: "reporter",
pwd: "reporter_password",
roles: [{ role: "read", db: "mydb" }]
});
# mongod.conf - Security settings
security:
authorization: enabled
net:
ssl:
mode: requireSSL
PEMKeyFile: /path/to/mongodb.pem
CAFile: /path/to/ca.pem
Connection with SSL
// Node.js connection with SSL
const { MongoClient } = require('mongodb');
const client = new MongoClient('mongodb://host:27017', {
ssl: true,
sslCA: fs.readFileSync('/path/to/ca.pem'),
sslCert: fs.readFileSync('/path/to/client.pem'),
sslKey: fs.readFileSync('/path/to/client.key'),
authSource: 'admin',
});
Replica Set (High Availability)
// Initialize replica set
rs.initiate({
_id: "myReplicaSet",
members: [
{ _id: 0, host: "mongo1:27017", priority: 2 },
{ _id: 1, host: "mongo2:27017", priority: 1 },
{ _id: 2, host: "mongo3:27017", priority: 1 }
]
});
// Connection string for replica set
mongodb://mongo1:27017,mongo2:27017,mongo3:27017/mydb?replicaSet=myReplicaSet&readPreference=secondaryPreferred
Backup & Recovery
# mongodump backup
mongodump --uri="mongodb://user:pass@host:27017/mydb" \
--out=/backup/$(date +%Y%m%d) \
--gzip
# mongorestore
mongorestore --uri="mongodb://user:pass@host:27017/mydb" \
--gzip /backup/20240115
# Continuous backup with oplog
mongodump --oplog --out=/backup/full
# Point-in-time recovery
mongorestore --oplogReplay --oplogLimit=1705315200 /backup/full
Performance Tuning
// Index best practices
db.collection.createIndex({ field: 1 }, { background: true });
// Compound indexes for common queries
db.orders.createIndex({ userId: 1, createdAt: -1 });
// TTL index for automatic expiration
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });
// Partial indexes for filtered queries
db.orders.createIndex(
{ status: 1 },
{ partialFilterExpression: { status: { $in: ["pending", "processing"] } } }
);
// Analyze query performance
db.orders.find({ userId: "123" }).explain("executionStats");
Monitoring Metrics
| Metric | Alert Threshold |
|---|---|
| Connection count | > 80% max |
| Replication lag | > 10 seconds |
| Query targeting | > 1000 docs examined/returned |
| Cache hit ratio | < 95% |
| Oplog window | < 24 hours |
| Disk usage | > 80% |
Monitoring Commands
// Server status
db.serverStatus();
// Current operations
db.currentOp({ "active": true, "secs_running": { "$gt": 5 } });
// Replication status
rs.status();
// Index usage stats
db.collection.aggregate([{ $indexStats: {} }]);
// Collection stats
db.collection.stats();
// Database profiler (slow queries)
db.setProfilingLevel(1, { slowms: 100 });
db.system.profile.find().sort({ ts: -1 }).limit(10);
Read/Write Concerns
// Write concern for durability
db.orders.insertOne(order, {
writeConcern: { w: "majority", j: true, wtimeout: 5000 }
});
// Read concern for consistency
db.orders.find({ userId: "123" }).readConcern("majority");
// Read preference for scaling reads
db.orders.find().readPref("secondaryPreferred");
Установить mongodb в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditВложенные файлы
FAQ
Что делает скилл mongodb?
MongoDB document database. Covers CRUD operations, aggregations, and indexes. Use when working with MongoDB. USE WHEN: user mentions "mongodb", "mongo", "document database", asks about "aggregation pipeline", "embedded documents", "BSON", "replica sets", "sharding", "atlas" DO NOT USE FOR: SQL databases - use `postgresql`/`mysql` instead, Redis - use `redis` instead, Elasticsearch - use `elasticsearch` instead, Relational data - use SQL skills
Как установить скилл mongodb?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл mongodb запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic