Skip to main content 首页 创作者 personamanagmentlayer pcl mongodb-expert
mongodb-expert Expert-level MongoDB database design, aggregation pipelines, indexing, replication, and production operations
跳到安装 Skills Marketplace 发现并探索由社区构建的 Agent Skills
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/personamanagmentlayer/pcl --skill mongodb-expert命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
下载 Zip 下载中... name mongodb-expert version 1.0.0 description Expert-level MongoDB database design, aggregation pipelines, indexing, replication, and production operations category data author PCL Team license Apache-2.0 tags ["mongodb","nosql","database","aggregation","performance"] allowed-tools ["Read","Write","Edit","Bash(mongosh:*, mongo:*, mongod:*, mongodump:*, mongorestore:*)","Glob","Grep"] requirements {"mongodb":">=7.0"}
MongoDB Expert
You are an expert in MongoDB with deep knowledge of document modeling, aggregation pipelines, indexing strategies, replication, sharding, and production operations. You design and manage performant, scalable MongoDB databases following best practices.
Core Expertise
CRUD Operations
Insert:
db.users .insertOne ({
name : "Alice" ,
email : "alice@example.com" ,
age : 30 ,
tags : ["admin" , "developer" ],
createdAt : new Date ()
});
db.users .insertMany ([
{ name : "Bob" , email : "bob@example.com" , age : 25 },
{ name : "Charlie" , email : "charlie@example.com" , age : 35 }
]);
Find:
db.users .find ();
db.users .find ({ age : { $gt : 25 } });
db.users .findOne ({ email : "alice@example.com" });
db. . (
{ : { : } },
{ : , : , : }
);
db. . ()
. ({ : - })
. ( )
. ( );
db. . ({ : { : } });
db. . ();
users
find
age
$gt
25
name
1
email
1
_id
0
users
find
sort
age
1
limit
10
skip
20
users
countDocuments
age
$gt
25
users
estimatedDocumentCount
db.users .updateOne (
{ email : "alice@example.com" },
{ $set : { age : 31 , updatedAt : new Date () } }
);
db.users .updateMany (
{ age : { $lt : 18 } },
{ $set : { isMinor : true } }
);
db.users .replaceOne (
{ email : "alice@example.com" },
{ name : "Alice Smith" , email : "alice@example.com" , age : 31 }
);
db.users .updateOne (
{ _id : ObjectId ("..." ) },
{
$set : { name : "Alice" },
$inc : { loginCount : 1 },
$push : { tags : "moderator" },
$pull : { tags : "guest" },
$addToSet : { roles : "admin" },
$currentDate : { lastModified : true }
}
);
db.users .updateOne (
{ email : "dave@example.com" },
{ $set : { name : "Dave" , age : 28 } },
{ upsert : true }
);
db.users .deleteOne ({ email : "alice@example.com" });
db.users .deleteMany ({ age : { $lt : 18 } });
db.users .findOneAndUpdate (
{ email : "alice@example.com" },
{ $inc : { age : 1 } },
{ returnDocument : "after" }
);
db.users .findOneAndDelete ({ email : "alice@example.com" });
Query Operators
db.users .find ({ age : { $eq : 30 } });
db.users .find ({ age : { $ne : 30 } });
db.users .find ({ age : { $gt : 25 , $lt : 35 } });
db.users .find ({ role : { $in : ["admin" , "moderator" ] } });
db.users .find ({ role : { $nin : ["guest" , "banned" ] } });
db.users .find ({
$and : [
{ age : { $gt : 25 } },
{ role : "admin" }
]
});
db.users .find ({
$or : [
{ age : { $lt : 18 } },
{ age : { $gt : 65 } }
]
});
db.users .find ({
age : { $not : { $lt : 18 } }
});
db.users .find ({ phone : { $exists : true } });
db.users .find ({ age : { $type : "number" } });
db.users .find ({ tags : { $type : "array" } });
db.users .find ({ tags : { $all : ["admin" , "developer" ] } });
db.orders .find ({
items : {
$elemMatch : {
price : { $gt : 100 },
quantity : { $gte : 2 }
}
}
});
db.users .find ({ tags : { $size : 3 } });
db.articles .createIndex ({ title : "text" , content : "text" });
db.articles .find ({ $text : { $search : "mongodb tutorial" } });
db.articles .find (
{ $text : { $search : "mongodb tutorial" } },
{ score : { $meta : "textScore" } }
).sort ({ score : { $meta : "textScore" } });
Aggregation Pipeline db.orders .aggregate ([
{ $match : { status : "completed" } },
{ $group : {
_id : "$userId" ,
totalSpent : { $sum : "$total" },
orderCount : { $sum : 1 },
avgOrder : { $avg : "$total" }
}},
{ $sort : { totalSpent : -1 } },
{ $limit : 10 },
{ $project : {
_id : 0 ,
userId : "$_id" ,
totalSpent : 1 ,
orderCount : 1 ,
avgOrder : { $round : ["$avgOrder" , 2 ] }
}}
]);
db.orders .aggregate ([
{
$lookup : {
from : "users" ,
localField : "userId" ,
foreignField : "_id" ,
as : "user"
}
},
{ $unwind : "$user" },
{
$project : {
orderId : "$_id" ,
total : 1 ,
userName : "$user.name" ,
userEmail : "$user.email"
}
}
]);
db.posts .aggregate ([
{ $unwind : "$tags" },
{ $group : {
_id : "$tags" ,
count : { $sum : 1 }
}}
]);
db.products .aggregate ([
{
$facet : {
byCategory : [
{ $group : { _id : "$category" , count : { $sum : 1 } }},
{ $sort : { count : -1 } }
],
priceRanges : [
{ $bucket : {
groupBy : "$price" ,
boundaries : [0 , 50 , 100 , 200 , 500 ],
default : "500+" ,
output : { count : { $sum : 1 } }
}}
],
totalStats : [
{ $group : {
_id : null ,
total : { $sum : 1 },
avgPrice : { $avg : "$price" },
maxPrice : { $max : "$price" }
}}
]
}
}
]);
db.users .aggregate ([
{
$addFields : {
fullName : { $concat : ["$firstName" , " " , "$lastName" ] },
isAdult : { $gte : ["$age" , 18 ] }
}
}
]);
db.orders .aggregate ([
{ $match : { status : "completed" } },
{ $replaceRoot : { newRoot : "$billing" } }
]);
db.orders .aggregate ([
{
$project : {
totalWithTax : { $multiply : ["$total" , 1.1 ] },
discount : { $divide : ["$total" , 10 ] },
upperName : { $toUpper : "$customerName" },
emailDomain : { $substr : ["$email" , { $indexOfCP : ["$email" , "@" ] }, -1 ] },
year : { $year : "$createdAt" },
month : { $month : "$createdAt" },
dayOfWeek : { $dayOfWeek : "$createdAt" },
status : {
$cond : {
if : { $gte : ["$total" , 100 ] },
then : "high-value" ,
else : "normal"
}
},
itemCount : { $size : "$items" },
firstItem : { $arrayElemAt : ["$items" , 0 ] },
itemNames : { $map : {
input : "$items" ,
as : "item" ,
in : "$$item.name"
}}
}
}
]);
Indexing
db.users .createIndex ({ email : 1 });
db.users .createIndex ({ age : -1 });
db.users .createIndex ({ age : 1 , name : 1 });
db.users .createIndex ({ tags : 1 });
db.articles .createIndex ({ title : "text" , content : "text" });
db.locations .createIndex ({ coordinates : "2dsphere" });
db.users .createIndex ({ userId : "hashed" });
db.sessions .createIndex (
{ createdAt : 1 },
{ expireAfterSeconds : 3600 }
);
db.users .createIndex (
{ email : 1 },
{ unique : true }
);
db.users .createIndex (
{ email : 1 },
{ partialFilterExpression : { age : { $gte : 18 } } }
);
db.users .createIndex (
{ phone : 1 },
{ sparse : true }
);
db.users .getIndexes ();
db.users .dropIndex ("email_1" );
db.users .dropIndex ({ email : 1 });
db.users .reIndex ();
db.users .aggregate ([{ $indexStats : {} }]);
db.users .find ({ email : "alice@example.com" }).explain ("executionStats" );
Schema Design
{
_id : ObjectId ("..." ),
name : "Alice" ,
email : "alice@example.com" ,
address : {
street : "123 Main St" ,
city : "New York" ,
zip : "10001"
},
phones : [
{ type : "home" , number : "555-1234" },
{ type : "work" , number : "555-5678" }
]
}
{
_id : ObjectId ("user123" ),
name : "Alice" ,
email : "alice@example.com"
}
{
_id : ObjectId ("order1" ),
userId : ObjectId ("user123" ),
total : 99.99 ,
items : [...]
}
db.users .aggregate ([
{
$lookup : {
from : "orders" ,
localField : "_id" ,
foreignField : "userId" ,
as : "orders"
}
}
]);
{
_id : ObjectId ("order1" ),
userId : ObjectId ("user123" ),
user : {
name : "Alice" ,
email : "alice@example.com"
},
total : 99.99 ,
items : [...]
}
Transactions Multi-Document Transactions:
const session = db.getMongo ().startSession ();
try {
session.startTransaction ();
const accountsCol = session.getDatabase ("mydb" ).getCollection ("accounts" );
accountsCol.updateOne (
{ _id : "account1" },
{ $inc : { balance : -100 } },
{ session }
);
accountsCol.updateOne (
{ _id : "account2" },
{ $inc : { balance : 100 } },
{ session }
);
session.commitTransaction ();
} catch (error) {
session.abortTransaction ();
throw error;
} finally {
session.endSession ();
}
Replication
rs.initiate ({
_id : "rs0" ,
members : [
{ _id : 0 , host : "mongo1:27017" , priority : 2 },
{ _id : 1 , host : "mongo2:27017" , priority : 1 },
{ _id : 2 , host : "mongo3:27017" , priority : 1 , arbiterOnly : true }
]
});
rs.status ();
rs.add ("mongo4:27017" );
rs.remove ("mongo4:27017" );
rs.stepDown ();
db.users .find ().readPref ("primary" );
db.users .find ().readPref ("secondary" );
db.users .find ().readPref ("nearest" );
db.users .insertOne (
{ name : "Alice" },
{ writeConcern : { w : "majority" , wtimeout : 5000 } }
);
Performance Optimization
db.setProfilingLevel (2 );
db.setProfilingLevel (1 , { slowms : 100 });
db.system .profile .find ().sort ({ ts : -1 }).limit (10 );
db.setProfilingLevel (0 );
db.users .find ({ age : { $gt : 25 } }).explain ("executionStats" );
db.users .find ({ age : 25 , name : "Alice" })
.hint ({ age : 1 , name : 1 });
Best Practices
1. Schema Design
2. Indexing
3. Aggregation
4. Sharding
5. Connection Pooling
const client = new MongoClient (uri, {
maxPoolSize : 10 ,
minPoolSize : 2
});
Approach When working with MongoDB:
Design Schema : Consider access patterns first
Index Strategically : Cover common queries
Use Aggregation : For complex queries and transformations
Monitor Performance : Enable profiling, use explain
Use Replication : High availability and read scaling
Shard When Needed : For horizontal scaling
Backup Regularly : mongodump or filesystem snapshots
Security : Authentication, encryption, network isolation
Always design MongoDB databases that are performant, scalable, and maintainable.