Skip to main content Skills Marketplace Discover and explore AI skills built by the community.
Related occupations SOC
Based on SOC occupation classification
Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
Copy promptShow prompt details A direct command skips the review prompt. Inspect the source before running it.
npx skills add https://github.com/bobmatnyc/claude-mpm-skills --skill mongodbThe command stays on one line. Scroll horizontally to inspect it before copying.
Prefer a local copy? Download the files currently available to SkillsMP.
Download Zip Downloading... More from this repository LinkedIn automation via the Linked API CLI - fetch profiles, search people and companies, send messages, manage connections, create posts, react, comment, and run Sales Navigator and custom workflows. Use when the user wants to interact with LinkedIn.
Xquik X data automation API - Use REST or MCP for tweet search, user lookup, follower exports, media downloads, monitors, webhooks, giveaway draws, and confirmation-gated X actions.
MCP (Model Context Protocol) - Build AI-native servers with tools, resources, and prompts. TypeScript/Python SDKs for Claude Desktop integration.
name mongodb description MongoDB - NoSQL document database with flexible schema design, aggregation pipelines, indexing strategies, and Spring Data integration user-invocable false disable-model-invocation true version 1.0.0 category toolchain author Claude MPM Team license MIT progressive_disclosure {"entry_point":{"summary":"Document-oriented NoSQL database with flexible schemas, powerful aggregation framework, horizontal scaling, and rich query language","when_to_use":"Building apps with flexible/evolving schemas, hierarchical data, real-time analytics, geospatial queries, or need horizontal scaling","quick_start":"1. Design documents (embedded vs referenced) 2. Create indexes for queries 3. Use aggregation for analytics 4. Implement proper connection pooling"}} context_limit 700 tags ["mongodb","nosql","database","document-database","aggregation","indexing","spring-data","schema-design"] requires_tools []
MongoDB - Document Database Patterns
Overview
MongoDB is a document-oriented NoSQL database that stores data in flexible, JSON-like documents. It excels at handling unstructured or semi-structured data, hierarchical relationships, and scenarios requiring horizontal scaling.
Key Features :
Flexible schema (schemaless documents)
Rich query language with secondary indexes
Aggregation framework for analytics
Horizontal scaling (sharding)
Replica sets for high availability
Change streams for real-time data
Geospatial and full-text search
When to Use MongoDB :
Rapidly evolving schemas
Hierarchical/nested data (embedded documents)
Real-time analytics with aggregation
Geospatial applications
Content management systems
IoT data ingestion
Catalog/inventory systems
When NOT to Use MongoDB :
Complex multi-table joins (use RDBMS)
ACID transactions across many documents (improved in 4.0+, but limited)
Strict schema enforcement requirements
Schema Design Fundamentals
Document Structure
{
"_id" : ObjectId ("507f1f77bcf86cd799439011" ),
"email" : "alice@example.com" ,
"name" : "Alice Johnson" ,
"profile" : {
"bio" : "Software developer" ,
"avatar" : "https://example.com/avatar.jpg" ,
"social" : {
"twitter" : "@alice" ,
"github" : "alice-dev"
}
},
"tags" : ["developer" , "python" , ],
: ( ),
: ( )
}
"mongodb"
"createdAt"
ISODate
"2024-01-15T10:30:00Z"
"updatedAt"
ISODate
"2024-01-20T14:22:00Z"
Embedded vs Referenced Documents Embedded (Denormalized) - Store related data in same document:
{
"_id" : ObjectId ("..." ),
"name" : "Alice" ,
"address" : {
"street" : "123 Main St" ,
"city" : "San Francisco" ,
"zipCode" : "94102"
}
}
{
"_id" : ObjectId ("..." ),
"orderNumber" : "ORD-2024-001" ,
"customer" : { "name" : "Alice" , "email" : "alice@example.com" },
"items" : [
{ "productId" : "SKU001" , "name" : "Widget" , "quantity" : 2 , "price" : 29.99 },
{ "productId" : "SKU002" , "name" : "Gadget" , "quantity" : 1 , "price" : 49.99 }
],
"total" : 109.97
}
Data is queried together frequently
Child data doesn't make sense without parent
1:1 or 1:Few relationships
Child data is bounded (won't grow unbounded)
Data doesn't need to be accessed independently
Referenced (Normalized) - Store references to other documents:
{
"_id" : ObjectId ("user123" ),
"name" : "Alice" ,
"email" : "alice@example.com"
}
{
"_id" : ObjectId ("post456" ),
"authorId" : ObjectId ("user123" ),
"title" : "MongoDB Schema Design" ,
"content" : "..." ,
"commentCount" : 42
}
{
"_id" : ObjectId ("comment789" ),
"postId" : ObjectId ("post456" ),
"authorId" : ObjectId ("user999" ),
"text" : "Great article!" ,
"createdAt" : ISODate ("2024-01-20T10:00:00Z" )
}
Many:Many relationships
1:Many with unbounded growth (comments, logs)
Data is accessed independently
Document size would exceed 16MB limit
Need atomic updates on referenced document
Hybrid Pattern (Extended Reference)
{
"_id" : ObjectId ("post456" ),
"title" : "MongoDB Best Practices" ,
"content" : "..." ,
"author" : {
"_id" : ObjectId ("user123" ),
"name" : "Alice" ,
"avatar" : "https://..."
},
"commentCount" : 42 ,
"lastCommentAt" : ISODate ("..." )
}
Query Patterns
Basic CRUD Operations
db.users .find ({ email : "alice@example.com" })
db.users .find ({ age : { $gte : 18 , $lte : 65 } })
db.users .find ({ tags : { $in : ["developer" , "designer" ] } })
db.users .find (
{ status : "active" },
{ name : 1 , email : 1 , _id : 0 }
)
db.users .findOne ({ email : "alice@example.com" })
db.users .insertOne ({ name : "Bob" , email : "bob@example.com" })
db.users .insertMany ([
{ name : "Charlie" , email : "charlie@example.com" },
{ name : "Diana" , email : "diana@example.com" }
])
db.users .updateOne (
{ email : "alice@example.com" },
{ $set : { name : "Alice Updated" , updatedAt : new Date () } }
)
db.users .updateMany (
{ status : "inactive" },
{ $set : { archived : true } }
)
db.users .updateOne (
{ email : "new@example.com" },
{ $set : { name : "New User" , createdAt : new Date () } },
{ upsert : true }
)
db.users .deleteOne ({ email : "bob@example.com" })
db.users .deleteMany ({ status : "deleted" })
Query Operators
db.products .find ({ price : { $gt : 100 } })
db.products .find ({ price : { $gte : 100 } })
db.products .find ({ price : { $lt : 50 } })
db.products .find ({ price : { $lte : 50 } })
db.products .find ({ price : { $ne : 0 } })
db.products .find ({ category : { $in : ["A" , "B" ] } })
db.products .find ({ category : { $nin : ["C" , "D" ] } })
db.users .find ({ $and : [{ age : { $gte : 18 } }, { status : "active" }] })
db.users .find ({ $or : [{ role : "admin" }, { role : "moderator" }] })
db.users .find ({ age : { $not : { $lt : 18 } } })
db.users .find ({ middleName : { $exists : true } })
db.users .find ({ age : { $type : "number" } })
db.posts .find ({ tags : "mongodb" })
db.posts .find ({ tags : { $all : ["mongodb" , "database" ] } })
db.posts .find ({ tags : { $size : 3 } })
db.posts .find ({ "tags.0" : "featured" })
db.users .find ({ "address.city" : "San Francisco" })
db.users .find ({ "profile.social.twitter" : { $exists : true } })
db.users .find ({ name : { $regex : /^alice/i } })
db.users .find ({ email : { $regex : /@example\.com$/ } })
Update Operators
db.users .updateOne (
{ _id : userId },
{
$set : { name : "New Name" },
$unset : { temporaryField : "" },
$rename : { oldName : "newName" },
$inc : { loginCount : 1 },
$mul : { price : 1.1 },
$min : { lowestScore : 50 },
$max : { highestScore : 100 },
$currentDate : { updatedAt : true }
}
)
db.posts .updateOne (
{ _id : postId },
{
$push : { tags : "new-tag" },
$addToSet : { tags : "unique-tag" },
$pop : { tags : 1 },
$pull : { tags : "old-tag" },
$pullAll : { tags : ["a" , "b" ] }
}
)
db.posts .updateOne (
{ _id : postId },
{
$push : {
comments : {
$each : [comment1, comment2],
$sort : { createdAt : -1 },
$slice : -100
}
}
}
)
db.posts .updateOne (
{ _id : postId, "comments._id" : commentId },
{ $set : { "comments.$.text" : "Updated comment" } }
)
db.posts .updateOne (
{ _id : postId },
{ $set : { "comments.$[elem].read" : true } },
{ arrayFilters : [{ "elem.userId" : currentUserId }] }
)
Indexing Strategies
Index Types
db.users .createIndex ({ email : 1 })
db.users .createIndex ({ createdAt : -1 })
db.orders .createIndex ({ customerId : 1 , createdAt : -1 })
db.users .createIndex ({ email : 1 }, { unique : true })
db.orders .createIndex (
{ createdAt : 1 },
{ partialFilterExpression : { status : "pending" } }
)
db.sessions .createIndex (
{ createdAt : 1 },
{ expireAfterSeconds : 3600 }
)
db.articles .createIndex ({ title : "text" , content : "text" })
db.locations .createIndex ({ coordinates : "2dsphere" })
db.posts .createIndex ({ tags : 1 })
db.users .createIndex ({ email : "hashed" })
Index Best Practices
db.users .createIndex ({ email : 1 , name : 1 , status : 1 })
db.users .find (
{ email : "alice@example.com" },
{ name : 1 , status : 1 , _id : 0 }
)
db.users .find ({ email : "alice@example.com" }).explain ("executionStats" )
db.users .getIndexes ()
db.users .dropIndex ("email_1" )
db.users .dropIndex ({ email : 1 , name : 1 })
Aggregation Pipeline
Pipeline Stages
db.orders .aggregate ([
{ $match : { status : "completed" } },
{ $group : { _id : "$customerId" , total : { $sum : "$amount" } } },
{ $sort : { total : -1 } },
{ $limit : 10 }
])
db.collection .aggregate ([
{ $match : { status : "active" , createdAt : { $gte : ISODate ("2024-01-01" ) } } },
{ $project : {
name : 1 ,
email : 1 ,
fullName : { $concat : ["$firstName" , " " , "$lastName" ] },
yearCreated : { $year : "$createdAt" }
}},
{ $addFields : {
totalPrice : { $multiply : ["$price" , "$quantity" ] }
}},
{ $group : {
_id : "$category" ,
count : { $sum : 1 },
totalRevenue : { $sum : "$amount" },
avgPrice : { $avg : "$price" },
maxPrice : { $max : "$price" },
products : { $push : "$name" },
uniqueTags : { $addToSet : "$tag" }
}},
{ $sort : { totalRevenue : -1 , count : 1 } },
{ $skip : 20 },
{ $limit : 10 },
{ $unwind : "$tags" },
{ $lookup : {
from : "users" ,
localField : "authorId" ,
foreignField : "_id" ,
as : "author"
}},
{ $unwind : "$author" },
{ $facet : {
results : [{ $skip : 0 }, { $limit : 10 }],
totalCount : [{ $count : "count" }]
}}
])
Real-World Aggregation Examples
db.orders .aggregate ([
{ $match : { status : "completed" } },
{ $group : {
_id : {
year : { $year : "$createdAt" },
month : { $month : "$createdAt" }
},
totalSales : { $sum : "$amount" },
orderCount : { $sum : 1 },
avgOrderValue : { $avg : "$amount" }
}},
{ $sort : { "_id.year" : -1 , "_id.month" : -1 } }
])
db.orders .aggregate ([
{ $match : { createdAt : { $gte : ISODate ("2024-01-01" ) } } },
{ $group : {
_id : "$customerId" ,
totalSpent : { $sum : "$amount" },
orderCount : { $sum : 1 },
lastOrder : { $max : "$createdAt" }
}},
{ $sort : { totalSpent : -1 } },
{ $limit : 10 },
{ $lookup : {
from : "customers" ,
localField : "_id" ,
foreignField : "_id" ,
as : "customer"
}},
{ $unwind : "$customer" },
{ $project : {
customerName : "$customer.name" ,
customerEmail : "$customer.email" ,
totalSpent : 1 ,
orderCount : 1 ,
lastOrder : 1
}}
])
db.orders .aggregate ([
{ $unwind : "$items" },
{ $lookup : {
from : "products" ,
localField : "items.productId" ,
foreignField : "_id" ,
as : "product"
}},
{ $unwind : "$product" },
{ $group : {
_id : "$product.category" ,
totalRevenue : { $sum : { $multiply : ["$items.quantity" , "$items.price" ] } },
unitsSold : { $sum : "$items.quantity" },
uniqueProducts : { $addToSet : "$product._id" }
}},
{ $addFields : {
uniqueProductCount : { $size : "$uniqueProducts" }
}},
{ $sort : { totalRevenue : -1 } }
])
Transactions (MongoDB 4.0+)
const session = client.startSession ();
try {
session.startTransaction ();
await accounts.updateOne (
{ _id : fromAccountId },
{ $inc : { balance : -amount } },
{ session }
);
await accounts.updateOne (
{ _id : toAccountId },
{ $inc : { balance : amount } },
{ session }
);
await transactions.insertOne (
{
from : fromAccountId,
to : toAccountId,
amount : amount,
createdAt : new Date ()
},
{ session }
);
await session.commitTransaction ();
} catch (error) {
await session.abortTransaction ();
throw error;
} finally {
session.endSession ();
}
Change Streams
const changeStream = db.orders .watch ([
{ $match : { "fullDocument.status" : "pending" } }
]);
changeStream.on ("change" , (change ) => {
console .log ("Change detected:" , change.operationType );
console .log ("Document:" , change.fullDocument );
if (change.operationType === "insert" ) {
processNewOrder (change.fullDocument );
}
});
const resumeToken = change._id ;
const changeStream = db.orders .watch ([], {
resumeAfter : resumeToken,
fullDocument : "updateLookup"
});
Spring Data MongoDB Integration
Entity Class @Document(collection = "users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User {
@Id
private String id;
@Indexed(unique = true)
private String email;
private String name;
@Field("password_hash")
private String passwordHash;
@DBRef
private List<Role> roles;
private Address address;
private List<String> tags;
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
@Version
private Long version;
}
@Data
public class Address {
private String street;
private String city;
private String zipCode;
@GeoSpatialIndexed(type = GeoSpatialIndexType.GEO_2DSPHERE)
private GeoJsonPoint location;
}
Repository Interface public interface UserRepository extends MongoRepository <User, String> {
Optional<User> findByEmail (String email) ;
List<User> findByNameContainingIgnoreCase (String name) ;
List<User> findByTagsContaining (String tag) ;
@Query("{ 'createdAt': { $gte: ?0 }, 'status': 'active' }")
List<User> findActiveUsersCreatedAfter (LocalDateTime date) ;
@Query(value = "{ 'email': ?0 }", fields = "{ 'name': 1, 'email': 1 }")
Optional<UserSummary> findSummaryByEmail (String email) ;
@Aggregation(pipeline = {
"{ $match: { 'status': 'active' } }",
"{ $group: { _id: '$country', count: { $sum: 1 } } }",
"{ $sort: { count: -1 } }"
})
List<CountryStats> getActiveUsersByCountry () ;
List<User> findByAddressLocationNear (Point location, Distance distance) ;
}
MongoTemplate for Complex Queries @Service
@RequiredArgsConstructor
public class UserService {
private final MongoTemplate mongoTemplate;
public List<User> searchUsers (UserSearchCriteria criteria) {
Query query = new Query ();
if (criteria.getName() != null ) {
query.addCriteria(Criteria.where("name" )
.regex(criteria.getName(), "i" ));
}
if (criteria.getTags() != null && !criteria.getTags().isEmpty()) {
query.addCriteria(Criteria.where("tags" )
.in(criteria.getTags()));
}
if (criteria.getCreatedAfter() != null ) {
query.addCriteria(Criteria.where("createdAt" )
.gte(criteria.getCreatedAfter()));
}
query.with(Sort.by(Sort.Direction.DESC, "createdAt" ));
query.with(PageRequest.of(criteria.getPage(), criteria.getSize()));
return mongoTemplate.find(query, User.class);
}
public AggregationResults<UserStats> getUserStatsByStatus () {
Aggregation aggregation = Aggregation.newAggregation(
Aggregation.match(Criteria.where("createdAt" )
.gte(LocalDateTime.now().minusMonths(1 ))),
Aggregation.group("status" )
.count().as("count" )
.avg("loginCount" ).as("avgLogins" ),
Aggregation.sort(Sort.Direction.DESC, "count" )
);
return mongoTemplate.aggregate(aggregation, "users" , UserStats.class);
}
public void bulkUpdateStatus (List<String> userIds, String newStatus) {
BulkOperations bulkOps = mongoTemplate.bulkOps(
BulkOperations.BulkMode.UNORDERED, User.class);
for (String userId : userIds) {
Query query = Query.query(Criteria.where("_id" ).is(userId));
Update update = Update.update("status" , newStatus)
.currentDate("updatedAt" );
bulkOps.updateOne(query, update);
}
bulkOps.execute();
}
}
Performance Optimization
Connection Pooling
spring:
data:
mongodb:
uri: mongodb:
auto-index-creation: false # Create indexes manually in production
# Connection pool settings (via URI)
# mongodb:
Query Optimization
db.users .find ({ status : "active" }, { name : 1 , email : 1 })
db.users .find ({ status : "active" }).hint ({ status : 1 , createdAt : -1 })
db.users .find ().sort ({ createdAt : -1 }).skip (20 ).limit (10 )
db.users .createIndex ({ optionalField : 1 }, { sparse : true })
db.users .find ({ optionalField : { $exists : true } })
Schema Optimization
{
_id : "sensor1_2024-01-15" ,
sensorId : "sensor1" ,
date : ISODate ("2024-01-15" ),
readings : [
{ ts : ISODate ("..." ), value : 23.5 },
{ ts : ISODate ("..." ), value : 24.1 },
],
count : 288
}
{
_id : "stats_2024-01" ,
month : "2024-01" ,
totalOrders : 1523 ,
totalRevenue : 152300.50 ,
avgOrderValue : 100.00 ,
topProducts : ["SKU001" , "SKU002" , "SKU003" ]
}
Best Practices
1. Schema Design
2. Indexing
3. Write Operations
db.orders .insertOne (doc, { writeConcern : { w : "majority" } })
4. Read Operations
db.orders .find ().readPref ("secondaryPreferred" )
5. Connection Management
Common Pitfalls
{ _id : "post1" , comments : [...thousands of comments...] }
{ _id : "comment1" , postId : "post1" , text : "..." }
db.users .find ({ email : "..." }).explain ()
Resources
Related Skills When using MongoDB, consider these complementary skills:
spring-boot : Java framework integration with Spring Data MongoDB
docker : Running MongoDB in containers
nodejs : MongoDB with Mongoose ODM
aggregation-pipelines : Advanced analytics patterns