spring-data-mongodb
БесплатноБез исполняемых скриптовНе проверенSpring Data MongoDB for Java/Spring Boot applications. Covers repositories, MongoTemplate, aggregations, and document mapping. USE WHEN: user mentions "spring…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Spring Data MongoDB - Quick Reference
Deep Knowledge: Use
mcp__documentation__fetch_docswith technology:spring-data-mongodbfor 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 (fil
Установить spring-data-mongodb в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл spring-data-mongodb?
Spring Data MongoDB for Java/Spring Boot applications. Covers repositories, MongoTemplate, aggregations, and document mapping. USE WHEN: user mentions "spring data mongodb", "MongoTemplate", "MongoRepository", "@Document", "Spring Boot MongoDB", "aggregation pipeline Java" DO NOT USE FOR: raw MongoDB driver - use `mongodb` instead, relational databases - use `spring-data-jpa` or `spring-data-jdbc` instead
Как установить скилл spring-data-mongodb?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл spring-data-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