实体类 Entity,以字段code为例mogo库查询通用模板
Aggregation aggregation = setAggregation(Entity, 0);
List<Entity> resultList =
mongoTemplate.aggregate(aggregation, "表名", Entity.class).getMappedResults();
public Aggregation setAggregation(Entity entity,int type) {
List<AggregationOperation> aggs = new ArrayList<>();
分组并且筛选
public Aggregation setAggregation(Entity entity,int type) {
List<AggregationOperation> aggs = new ArrayList<>();
aggs.add(Aggregation.group("code").first("code").as("code"));
aggs.add(Aggregation.sort(ASC, "code"));//排序
aggs.add(Aggregation.project("code"));//要展示的字段
aggs.add(Aggregation.match(Criteria.where("code").ne(null)));//不等于null
aggs.add(Aggregation.match(Criteria.where("code").ne("")));//不等于空字符串
模糊查询-相当于mysql like
aggs.add(Aggregation.match(Criteria.where("name").regex("测试")));
Integer pageSize = 20;
Integer pageNumber = 1;
if (type == 0) {
这里处理分页
if (pageNumber != null && pageSize != null) {
aggs.add(Aggregation.skip((pageNumber - 1) * pageSize));
aggs.add(Aggregation.limit(pageSize));
}
}
if (type == 1) {
计算数量
aggs.add(Aggregation.count().as("totalCount"));
}
Aggregation aggregation = Aggregation.newAggregation(aggs)
.withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
return aggregation;
}
代码示例
Aggregation aggregation = setAggregation(entity, 0);
List<Entity > resultList =
mongoTemplate.aggregate(aggregation, "表名", Entity .class).getMappedResults();
/**
* @param Entity
* @param type 0-分页查询、1-统计条数
* @return
*/
public Aggregation setAggregation(Entity entity,int type) {
List<AggregationOperation> aggs = new ArrayList<>();
aggs.add(Aggregation.group("code").first("code").as("code")
);
aggs.add(Aggregation.sort(ASC, "code"));
aggs.add(Aggregation.project("code"));
aggs.add(Aggregation.match(Criteria.where("code").ne(null)));
aggs.add(Aggregation.match(Criteria.where("code").ne("")));
if (entity.getCode() != null && !entity.getCode.equals("")) {
aggs.add(Aggregation.match(Criteria.where("code").regex(entity.getCode)));
}
Integer pageSize = 20;
Integer pageNumber = 1;
if (type == 0) {
if (pageNumber != null && pageSize != null) {
aggs.add(Aggregation.skip((pageNumber - 1) * pageSize));
aggs.add(Aggregation.limit(pageSize));
}
}
if (type == 1) {
aggs.add(Aggregation.count().as("totalCount"));
}
Aggregation aggregation = Aggregation.newAggregation(aggs)
.withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build());
return aggregation;
}
```