Java中如何使用Mongo的lookup关键字
1. pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
2. 实体
@Data
@Document("task_ver")
public class TaskVer {
@Field("taskid")
private Integer taskId;
@Field("ver")
private Integer ver;
@Field("flowid")
private Integer flowId;
@Field("flowver")
private Integer flowVer;
@Field("verseq")
private Integer verSeq;
@Field("versource")
private Integer verSource;
@Field("taskcn")
private String taskCn;
@Field("tasken")
private String taskEn;
}
@Data
@Document("task_alg_ver")
public class TaskAlgVer {
@Field("taskid")
private Integer taskId;
@Field("ver")
private Integer ver;
@Field("info")
private String info;
@Field("para")
private String para;
}
@Data
public class TaskVo extends TaskOrchVer {
//注意这里lookup直接使用TaskAlgVer实体会映射失败
@Field("taskAlgVer")
private List<JSONObject> taskAlgVer;
}
3. 代码实现
Criteria criteria = new Criteria();
//过滤空间分析类型8
criteria.and("tasktype").is(8);
criteria.and("status").in(Arrays.asList(2, 21));
if (StringUtils.hasText(analysisListVo.getName())) {
criteria.and("taskcn").regex("^.*" + analysisListVo.getName() + ".*$");
}
MatchOperation matchOperation = Aggregation.match(criteria);
LookupOperation algLook = LookupOperation.newLookup().from("task_ver_alg").localField("taskid").foreignField("taskid").as("taskAlgVer");
// UnwindOperation algUnwind = Aggregation.unwind("taskVerAlgs", true);
//排序
SortOperation sort = null;
if (StringUtils.hasText(analysisListVo.getSortField())) {
sort = Aggregation.sort(Sort.by(new Sort.Order(analysisListVo.getSortType() == -1 ? Sort.Direction.DESC : Sort.Direction.ASC, analysisListVo.getSortField().toLowerCase())));
} else {
sort = Aggregation.sort(Sort.by(new Sort.Order(analysisListVo.getSortType() == -1 ? Sort.Direction.DESC : Sort.Direction.ASC, "inserttime")));
}
long pageNumber = analysisListVo.getCurPage();
long pageSize = analysisListVo.getPageSize();
ResultWrapper<TaskVo> page = new ResultWrapper<>();
page.setCurPage(pageNumber);
page.setPageSize(pageSize);
SkipOperation skip = Aggregation.skip((pageNumber - 1) * pageSize);
LimitOperation limit = Aggregation.limit(pageSize);
AggregationOptions aggregationOptions = AggregationOptions.builder().allowDiskUse(true).build();
Aggregation aggregation = Aggregation.newAggregation(matchOperation, algLook, sort, skip, limit).withOptions(aggregationOptions);
Aggregation countAggregation = Aggregation.newAggregation(matchOperation, algLook, sort).withOptions(aggregationOptions);
long count = primaryMongoTemplate.aggregate(countAggregation, "task_ver", TaskVo.class).getMappedResults().size();
page.setTotal(count);
long totalPage = count / pageSize;
page.setTotalPage(count % pageSize == 0 ? totalPage : (totalPage + 1));
List<TaskVo> tasks = primaryMongoTemplate.aggregate(aggregation, "task_ver", TaskVo.class).getMappedResults();
page.setDatasList(tasks);