关于 mongodb-atlas
mongodb-atlas 是面向 MongoDB 与 MongoDB Atlas 开发工作的技能,适用于处理数据模型、查询和数据库运维的开发者。内容涵盖 Prisma、索引、聚合、性能分析及 Atlas CLI 示例。
主要功能
- 01MongoDB 查询与模式示例
- 02聚合管道模式
- 03Prisma MongoDB 操作
- 04索引与查询优化
- 05Atlas CLI 集群命令
适用场景
- 01设计 MongoDB 模式与集合
- 02构建成员数据聚合报告
- 03分析索引使用情况和慢查询
- 04通过 Atlas CLI 管理集群
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ thelobbi/ claude --skill mongodb-atlas安装后在 Claude Code 中输入/mongodb-atlas确认已加载。
详细介绍
MongoDB Atlas 技能
为 Alpha Members Platform 提供全面的 MongoDB 和 MongoDB Atlas 能力。
何时使用此技能
在处理以下任务时启用此技能:
- MongoDB 查询开发
- 架构设计与建模
- 聚合管道
- 索引优化
- Prisma MongoDB 集成
- Atlas 集群管理
- 数据库性能调优
快速参考
Docker 命令
# Start local MongoDB
docker-compose up mongodb -d
# Connect to MongoDB shell
docker exec -it mongodb mongosh -u root -p rootpassword
# Check MongoDB logs
docker logs mongodb -f --tail=100
MongoDB Shell 命令
// Switch to database
use member_db
// List collections
show collections
// Find documents
db.members.find({ status: "ACTIVE" }).limit(10)
// Insert document
db.members.insertOne({ email: "[email protected]", status: "PENDING" })
// Update document
db.members.updateOne(
{ email: "[email protected]" },
{ $set: { status: "ACTIVE" } }
)
// Aggregation
db.members.aggregate([
{ $match: { status: "ACTIVE" } },
{ $group: { _id: "$profile.company", count: { $sum: 1 } } }
])
连接字符串
# Local Docker
mongodb://root:rootpassword@localhost:27017/member_db?authSource=admin
# Atlas (example)
mongodb+srv://user:[email protected]/member_db?retryWrites=true&w=majority
架构设计
Prisma MongoDB 架构
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model Member {
id String @id @default(auto()) @map("_id") @db.ObjectId
keycloakUserId String @unique
email String @unique
firstName String
lastName String
status MemberStatus @default(PENDING)
profile MemberProfile? // Embedded
addresses MemberAddress[] // Embedded array
memberships Membership[] // Relation
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@index([status])
@@index([email])
}
type MemberProfile {
jobTitle String?
company String?
timezone String @default("UTC")
}
type MemberAddress {
type AddressType
street1 String
city String
state String
postalCode String
}
集合
members
{
_id: ObjectId("..."),
keycloakUserId: "uuid",
email: "[email protected]",
firstName: "John",
lastName: "Doe",
status: "ACTIVE",
profile: {
jobTitle: "Engineer",
company: "Acme Corp"
},
addresses: [
{ type: "HOME", street1: "123 Main St", ... }
],
createdAt: ISODate("..."),
updatedAt: ISODate("...")
}
memberships
{
_id: ObjectId("..."),
memberId: ObjectId("..."),
type: "INDIVIDUAL",
level: "PREMIUM",
status: "ACTIVE",
startDate: ISODate("..."),
payment: {
method: "card",
amount: 99.99,
currency: "USD"
}
}
member_activities
{
_id: ObjectId("..."),
memberId: ObjectId("..."),
action: "LOGIN",
category: "AUTH",
ipAddress: "192.168.1.1",
createdAt: ISODate("...")
}
索引
推荐索引
// Members collection
db.members.createIndex({ keycloakUserId: 1 }, { unique: true })
db.members.createIndex({ email: 1 }, { unique: true })
db.members.createIndex({ status: 1, createdAt: -1 })
db.members.createIndex({ "profile.company": 1 })
// Text search
db.members.createIndex({
firstName: "text",
lastName: "text",
email: "text",
"profile.company": "text"
})
// Memberships
db.memberships.createIndex({ memberId: 1 })
db.memberships.createIndex({ status: 1, endDate: 1 })
// Activities (with TTL)
db.member_activities.createIndex({ memberId: 1, createdAt: -1 })
db.member_activities.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 31536000 } // 1 year TTL
)
聚合管道
成员统计
db.members.aggregate([
{ $facet: {
byStatus: [
{ $group: { _id: "$status", count: { $sum: 1 } } }
],
byMonth: [
{ $group: {
_id: { $dateToString: { format: "%Y-%m", date: "$createdAt" } },
count: { $sum: 1 }
}
},
{ $sort: { _id: 1 } }
],
total: [{ $count: "count" }]
}
}
])
成员及其会员关系
db.members.aggregate([
{ $match: { _id: ObjectId("...") } },
{ $lookup: {
from: "memberships",
localField: "_id",
foreignField: "memberId",
as: "memberships"
}
}
])
Prisma 操作
// Find member
const member = await prisma.member.findUnique({
where: { email: "[email protected]" },
include: { memberships: true }
});
// Create member with embedded profile
const newMember = await prisma.member.create({
data: {
email: "[email protected]",
firstName: "Jane",
lastName: "Doe",
keycloakUserId: "uuid",
profile: {
jobTitle: "Manager",
company: "Acme"
}
}
});
// Update with push to array
const updated = await prisma.member.update({
where: { id: "..." },
data: {
addresses: {
push: {
type: "WORK",
street1: "456 Office Blvd",
city: "Boston",
state: "MA",
postalCode: "02102"
}
}
}
});
// Aggregation with Prisma
const stats = await prisma.member.groupBy({
by: ['status'],
_count: true
});
性能优化
查询优化
// Use projection to limit returned fields
db.members.find(
{ status: "ACTIVE" },
{ firstName: 1, lastName: 1, email: 1 }
)
// Use covered queries
db.members.find(
{ email: "[email protected]" },
{ _id: 0, email: 1, status: 1 }
).hint({ email: 1, status: 1 })
// Explain query plan
db.members.find({ status: "ACTIVE" }).explain("executionStats")
索引分析
// Get index usage stats
db.members.aggregate([{ $indexStats: {} }])
// Find unused indexes
db.members.aggregate([
{ $indexStats: {} },
{ $match: { "accesses.ops": 0 } }
])
Atlas CLI 命令
# Login to Atlas
atlas auth login
# List clusters
atlas clusters list --projectId <projectId>
# Create cluster
atlas clusters create alpha-dev \
--projectId <projectId> \
--provider AWS \
--region US_EAST_1 \
--tier M10
# Get connection string
atlas clusters connectionStrings describe alpha-dev
项目文件
- Prisma 架构:
prisma/schema.prisma - MongoDB 初始化:
infrastructure/mongo-init/01-init-db.js - Docker:
docker/docker-compose.yml(mongodb 服务)
相关 Agent
- mongodb-atlas-admin - 集群管理
- mongodb-schema-designer - 架构设计
- mongodb-query-optimizer - 性能调优
- mongodb-aggregation-specialist - 复杂查询
故障排除
# Check MongoDB connection
docker exec mongodb mongosh --eval "db.adminCommand('ping')"
# Check replication status
docker exec mongodb mongosh --eval "rs.status()"
# Analyze slow queries
db.setProfilingLevel(1, { slowms: 100 })
db.system.profile.find().sort({ millis: -1 }).limit(10)
评论
支持 Markdown