Token导航 LogoToken导航TokenDH.com
研究检索external-servicegithub未标认证来源可访问许可证需确认审计通过

spring-data-mongodbspring 数据 MongoDB

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

699

周安装

28

GitHub Stars

12

下载量

226
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-data-mongodb(spring 数据 MongoDB)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/spring-data-mongodb
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill spring-data-mongodb
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill spring-data-mongodb

简介

在 Spring 应用中集成 MongoDB 文档数据库,实现灵活的数据建模。

  • 适用于内容管理、用户行为记录或半结构化数据存储等场景。
  • 支持基于 MongoTemplate 的 CRUD 操作和 Repository 抽象层。
  • 注意集合索引设计和分片策略,生产部署前应验证查询性能。
  • 技能来源为 claude-dev-suite 公共代码库。

SKILL.md

Spring Data MongoDB - Quick Reference

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: spring-data-mongodb for comprehensive documentation.

Setup

Dependencies (Maven)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

Configuration

spring:
  data:
    mongodb:
      uri: mongodb://localhost:27017/mydb
      # Or explicit
      host: localhost
      port: 27017
      database: mydb
      username: user
      password: secret
      authentication-database: admin

Entity Mapping

Basic Document

@Document(collection = "products")
public class Product {
    @Id
    private String id;

    @Field("product_name")
    private String name;

    @Indexed
    private String category;

    private BigDecimal price;

    @CreatedDate
    private LocalDateTime createdAt;

    @LastModifiedDate
    private LocalDateTime updatedAt;
}

Embedded Documents

@Document(collection = "orders")
public class Order {
    @Id
    private String id;

    private Customer customer;           // Embedded
    private List<OrderItem> items;       // Embedded list
    private Address shippingAddress;     // Embedded
}

// No @Document - embedded class
public class OrderItem {
    private String productId;
    private String productName;
    private int quantity;
    private BigDecimal price;
}

References

@Document(collection = "posts")
public class Post {
    @Id
    private String id;
    private String title;

    @DBRef
    private User author;                 // Lazy loaded reference

    // Manual reference (preferred for performance)
    private String authorId;
}

Repository Pattern

Basic Repository

public interface ProductRepository extends MongoRepository<Product, String> {

    // Derived queries
    List<Product> findByCategory(String category);
    List<Product> findByPriceLessThan(BigDecimal price);
    List<Product> findByCategoryAndPriceBetween(
        String category, BigDecimal min, BigDecimal max);

    // Sorting
    List<Product> findByCategoryOrderByPriceDesc(String category);

    // Limiting
    List<Product> findTop5ByCategoryOrderByPriceAsc(String category);

    // Exists/Count
    boolean existsByName(String name);
    long countByCategory(String category);
}

@Query Annotation

public interface ProductRepository extends MongoRepository<Product, String> {

    @Query("{ 'category': ?0, 'price': { $lte: ?1 } }")
    List<Product> findByCategoryWithMaxPrice(String category, BigDecimal maxPrice);

    @Query("{ 'tags': { $in: ?0 } }")
    List<Product> findByAnyTag(List<String> tags);

    @Query("{ 'name': { $regex: ?0, $options: 'i' } }")
    List<Product> searchByName(String keyword);

    // Projection
    @Query(value = "{ 'category': ?0 }", fields = "{ 'name': 1, 'price': 1 }")
    List<Product> findNameAndPriceByCategory(String category);
}

Aggregation in Repository

@Aggregation(pipeline = {
    "{ $match: { status: 'COMPLETED' } }",
    "{ $group: { _id: '$customerId', total: { $sum: '$amount' } } }",
    "{ $sort: { total: -1 } }",
    "{ $limit: 10 }"
})
List<CustomerTotal> findTopCustomers();

MongoTemplate

CRUD Operations

@Service
@RequiredArgsConstructor
public class ProductService {
    private final MongoTemplate mongoTemplate;

    // Create
    public Product save(Product product) {
        return mongoTemplate.save(product);
    }

    // Insert (fails if exists)
    public Product insert(Product product) {
        return mongoTemplate.insert(product);
    }

    // Read
    public Product findById(String id) {
        return mongoTemplate.findById(id, Product.class);
    }

    public List<Product> findByCategory(String category) {
        Query query = Query.query(Criteria.where("category").is(category));
        return mongoTemplate.find(query, Product.class);
    }

    // Update
    public UpdateResult updatePrice(String id, BigDecimal price) {
        Query query = Query.query(Criteria.where("id").is(id));
        Update update = Update.update("price", price);
        return mongoTemplate.updateFirst(query, update, Product.class);
    }

    // Delete
    public DeleteResult delete(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return mongoTemplate.remove(query, Product.class);
    }
}

Complex Queries

public List<Product> search(ProductFilter filter) {
    Query query = new Query();

    // Multiple criteria
    if (filter.getCategory() != null) {
        query.addCriteria(Criteria.where("category").is(filter.getCategory()));
    }

    if (filter.getMinPrice() != null && filter.getMaxPrice() != null) {
        query.addCriteria(Criteria.where("price")
            .gte(filter.getMinPrice())
            .lte(filter.getMaxPrice()));
    }

    // OR condition
    if (filter.getKeywords() != null) {
        query.addCriteria(new Criteria().orOperator(
            Criteria.where("name").regex(filter.getKeywords(), "i"),
            Criteria.where("description").regex(filter.getKeywords(), "i")
        ));
    }

    // Pagination
    query.with(PageRequest.of(filter.getPage(), filter.getSize()));

    // Sorting
    query.with(Sort.by(Sort.Direction.DESC, "createdAt"));

    // Projection
    query.fields().include("name", "price", "category");

    return mongoTemplate.find(query, Product.class);
}

Aggregation Framework

Basic Pipeline

public List<CategoryStats> getCategoryStats() {
    Aggregation agg = Aggregation.newAggregation(
        Aggregation.match(Criteria.where("active").is(true)),
        Aggregation.group("category")
            .count().as("count")
            .avg("price").as("avgPrice")
            .sum("stock").as("totalStock"),
        Aggregation.sort(Sort.Direction.DESC, "count")
    );

    return mongoTemplate.aggregate(agg, "products", CategoryStats.class)
        .getMappedResults();
}

Lookup (Join)

Aggregation agg = Aggregation.newAggregation(
    Aggregation.lookup("users", "userId", "_id", "user"),
    Aggregation.unwind("user"),
    Aggregation.project()
        .andInclude("orderNumber", "total")
        .and("user.name").as("customerName")
);

Unwind Arrays

Aggregation agg = Aggregation.newAggregation(
    Aggregation.unwind("items"),
    Aggregation.group("items.productId")
        .sum("items.quantity").as("totalSold")
        .first("items.productName").as("productName"),
    Aggregation.sort(Sort.Direction.DESC, "totalSold"),
    Aggregation.limit(10)
);

Indexes

Annotations

@Document(collection = "products")
@CompoundIndex(name = "category_price", def = "{'category': 1, 'price': -1}")
public class Product {

    @Indexed(unique = true)
    private String sku;

    @Indexed
    private String category;

    @TextIndexed(weight = 3)
    private String name;

    @TextIndexed
    private String description;

    @Indexed(expireAfter = "30d")
    private LocalDateTime expiresAt;
}

Programmatic

mongoTemplate.indexOps(Product.class).ensureIndex(
    new Index()
        .on("category", Sort.Direction.ASC)
        .on("price", Sort.Direction.DESC)
        .named("category_price_idx")
);

Update Operations

Update Operators

Update update = new Update()
    .set("name", "New Name")
    .inc("viewCount", 1)
    .push("tags", "new-tag")
    .addToSet("categories", "electronics")
    .unset("deprecatedField")
    .currentDate("lastModified");

mongoTemplate.updateFirst(query, update, Product.class);

Upsert

mongoTemplate.upsert(query, update, Product.class);

Bulk Operations

BulkOperations bulkOps = mongoTemplate.bulkOps(BulkMode.ORDERED, Product.class);
products.forEach(p -> bulkOps.insert(p));
bulkOps.execute();

Testing with Testcontainers

@DataMongoTest
@Testcontainers
class ProductRepositoryTest {

    @Container
    @ServiceConnection
    static MongoDBContainer mongo = new MongoDBContainer("mongo:7.0");

    @Autowired
    private ProductRepository repository;

    @Test
    void shouldFindByCategory() {
        repository.save(new Product("Phone", "electronics", BigDecimal.valueOf(999)));

        List<Product> found = repository.findByCategory("electronics");

        assertThat(found).hasSize(1);
    }
}

Common Query Methods

MethodMongoDB Equivalent
findByX(x){x: x}
findByXAndY(x, y){x: x, y: y}
findByXOrY(x, y){$or: [{x: x}, {y: y}]}
findByXBetween(a, b){x: {$gte: a, $lte: b}}
findByXLessThan(x){x: {$lt: x}}
findByXIn(list){x: {$in: list}}
findByXRegex(pattern){x: {$regex: pattern}}
findByXExists(bool){x: {$exists: bool}}

When NOT to Use This Skill

  • Raw MongoDB driver - Use mongodb skill for driver-level operations
  • Relational data - Use spring-data-jpa or spring-data-jdbc
  • Full-text search focus - Consider spring-data-elasticsearch
  • Graph relationships - Use spring-data-neo4j

Anti-Patterns

Anti-PatternProblemSolution
Using @DBRef everywhereN+1 queries, slowEmbed or manual references
Missing indexesSlow queriesAdd @Indexed, compound indexes
Fetching full documentsWasted bandwidthUse projections, fields()
Transactions without replica setTransactions failConfigure replica set
Documents > 16MBInsert failsRedesign, use GridFS for large files
Dynamic field typesQuery issuesUse consistent schemas

Quick Troubleshooting

ProblemDiagnosticFix
Connection refusedCheck MongoDB runningStart MongoDB, check URI
Duplicate key errorCheck @Id or unique indexHandle or use upsert
Query returns emptyCheck field namesVerify @Field mapping matches DB
Slow aggregationCheck stagesAdd $match early, use indexes
Transaction failsCheck replica setConfigure replica set or remove transaction

Reference Documentation

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

35.38%
按下载量换算80

Claude

29.08%
按下载量换算66

Cursor

19.11%
按下载量换算43

Gemini CLI

8.4%
按下载量换算19

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills