好巧不巧翻了一下 spring-data-mongo的文档,一不小心被我发现了新东西。
@Aggregate
终于不用繁琐的写 mongoOperation.aggregate(Aggregate.newAggregate(Aggregate.match,Aggregate.group))
版本是在springboot 2.2.0.RELEASE
使用方式举例:来之spring-data-mongo
public interface PersonRepository extends CrudReppsitory<Person, String> {
@Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $firstname } } }")
List<PersonAggregate> groupByLastnameAndFirstnames();
@Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $firstname } } }")
List<PersonAggregate> groupByLastnameAndFirstnames(Sort sort);
@Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $?0 } } }")
List<PersonAggregate> groupByLastnameAnd(String property);
@Aggregation("{ $group: { _id : $lastname, names : { $addToSet : $?0 } } }")
List<PersonAggregate> groupByLastnameAnd(String property, Pageable page);
@Aggregation("{ $group : { _id : null, total : { $sum : $age } } }")
SumValue sumAgeUsingValueWrapper();
@Aggregation("{ $group : { _id : null, total : { $sum : $age } } }")
Long sumAge();
@Aggregation("{ $group : { _id : null, total : { $sum : $age } } }")
AggregationResults<SumValue> sumAgeRaw();
@Aggregation("{ '$project': { '_id' : '$lastname' } }")
List<String> findAllLastnames();
}
public class PersonAggregate {
private @Id String lastname;
private List<String> names;
public PersonAggregate(String lastname, List<String> names) {
// ...
}
// Getter / Setter omitted
}
public class SumValue {
private final Long total;
public SumValue(Long total) {
// ...
}
// Getter omitted
}
spring真香啊
本文介绍了Spring Data MongoDB中@Aggregation注解的使用方法,通过示例展示了如何简化MongoDB的聚合操作,如按姓氏分组名字、计算年龄总和等。Spring Boot 2.2.0.RELEASE版本引入了这一特性,极大地提高了开发效率。
2万+

被折叠的 条评论
为什么被折叠?



